package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.core.filter.CookieFilter;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.affaircase.AffairRecord;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseCompanyOwner;
import com.qili.entity.base.BaseDict;
import com.qili.entity.jc.JcProject;
import com.qili.entity.supervisor.*;
import com.qili.entity.supplier.*;
import com.qili.entity.supplier.dto.*;
import com.qili.entity.sys.*;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.ZxProject;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.AffairService;
import com.qili.service.SysUserService;
import com.qili.service.WorkflowService;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.affairCase.AffairRecordService;
import com.qili.service.base.BaseCompanyOwnerService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.jc.JcProjectService;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.*;
import com.qili.service.sys.*;
import com.qili.service.zx.ZxProjectService;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/3/12
 * @description 供需系统
 */
@Controller
@Slf4j
@RequestMapping("/supplier")
public class SupplierProjectManagerController {

    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    ProjectPlaceService projectPlaceService;
    @Autowired
    OperQueryRecordService operQueryRecordService;
    @Autowired
    AffairCaseService affairCaseService;

    @Autowired
    WorkflowService workflowService;

    @Autowired
    AffairService affairService;

    @Autowired
    SupplierProjectManagerChangeService supplierProjectManagerChangeService;
    @Autowired
    ProjectPlaceChangeService projectPlaceChangeService;

    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;

    @Autowired
    SupervisorFileTempService supervisorFileTempService;

    @Value("${supervisor.tempPath}")
    private String tempPath;

    @Autowired
    SupervisorFileService supervisorFileService;

    @Autowired
    SupervisorProjectModifiedRecordService supervisorProjectModifiedRecordService;
    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;

    @Autowired
    AffairRecordService affairRecordService;
    @Autowired
    ProjectCollectService projectCollectService;
    @Autowired
    SupervisorProjectService supervisorProjectService;
    @Autowired
    OaDataService oaDataService;
    @Autowired
    private SysUserProjectService sysUserProjectService;
    @Autowired
    private SysUserCertificateService userCertificateService;

    @Autowired
    UploadUtil uploadUtil;

    @Autowired
    private SysUserEducationService userEducationService;

    @Autowired
    private  SupplierProjectPubNoticeService   supplierProjectPubNoticeService;
    @Autowired
    private BaseCompanyOwnerService baseCompanyOwnerService;

    @Autowired
    ZxProjectService zxProjectService;

    @Autowired
    JcProjectService jcProjectService;

    @Autowired
    SysLogMapper sysLogMapper;
    private static final Logger log = LoggerFactory.getLogger(CookieFilter.class);
    /**
     * @param request
     * @Author:zhaoyongke
     * @Description: 系统首页
     * @Date:13:38 2021/3/13
     */
    @GetMapping(value = "index")
    @RequiresPermissions("gx:index")
    public String index(HttpServletRequest request) {
        String userId = CommonUtil.getUserId();
        SysUser sysUser=sysUserService.selectByPrimaryKey(userId);
        if(sysUser==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }
        return "index/supplierIndex";
    }

    /**
     * 系统进来后的首页
     * @param request
     * @Author:zhaoyongke
     * @Description:
     * @Date:13:38 2021/3/13
     */
    @GetMapping(value = "firstIndex")
    @RequiresPermissions("supplier:menuIndex")
    public String firstIndex(HttpServletRequest request) {

        OperQueryRecordDTO dto = new OperQueryRecordDTO();
        Page<OperQueryRecordDTO> tPage = PageHelper.startPage(0, 10);
        List<OperQueryRecordDTO> operQueryRecordDTOS = operQueryRecordService.selectKeyWordHot(dto);
        request.setAttribute("listrecords", operQueryRecordDTOS);

        SysUser sysUser = getSysUser();
        //001 供方 002 需方
        String gxType = sysUser.getGxType();

        if ("002".equals(gxType)) {
            request.setAttribute("gxtype", "x");
        }
        return "projectManager/index";
    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:项目列表
     * @Date:17:59 2021/3/25
     */
    @GetMapping(value = "projectListIndex")
    @RequiresPermissions("supplier:projectList")
    public String projectListIndex(Model model) {
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("provincelist", provincelist);
        return "projectManager/projectListIndex";
    }

    /**
     * @param model
     * @param dto
     * @Author:zhaoyongke
     * @Description:公司信息
     * @Date:14:46 2021/4/2
     */
    @GetMapping(value = "companyDetail")
    public String companyDetail(Model model, SupplierProjectAcceptDTO dto) {
        String supAcceptId = dto.getSupAcceptId();
        SupplierProjectAccept accept = supplierProjectAcceptService.selectByPrimaryKey(supAcceptId);
        String acceptBy = accept.getAcceptBy();
        SysUser sysUser = sysUserService.selectByPrimaryKey(acceptBy);
        // 保存形式  001 （保存公司Id） 002 保存（应接人的Id）
        String companyId = accept.getCompanyId();
        String comType = accept.getComType();
        String companyName = "";
        String dwxz = "";
        String jgdm = "";
        String url="";
        if ("001".equals(comType)) {
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName = baseCompany.getBcName();
            jgdm = baseCompany.getBcJgdm();
            String dwxzcode = baseCompany.getBcDwxz();
            dwxz=dwxzcode;
         /*   if ("001".equals(dwxzcode)) {
                dwxz = "企业";
            } else if ("002".equals(dwxzcode)) {
                dwxz = "机关";
            }*/
            url="projectManager/companyDetail";
        } else {
            companyName = sysUser.getCompanyName();
            String dwxzcode = sysUser.getCompanyType();
            if ("001".equals(dwxzcode)) {
                dwxz = "企业";
            } else if ("002".equals(dwxzcode)) {
                dwxz = "机关";
            }
            jgdm = sysUser.getJgcode();
            //公司业绩列表和证明文件
            SysUserProject userProject = new SysUserProject();
            userProject.setSuId(sysUser.getId());
            List<SysUserProject> userProjectList = sysUserProjectService.selectUserYj(userProject);
            model.addAttribute("userYj",userProjectList);
            //公司资质证明文件
            SysUserCertificate userCertificate = new SysUserCertificate();
            userCertificate.setSuId(sysUser.getId());
            List<SysUserCertificate> sysUserCertificates = userCertificateService.selectUserCert(userCertificate);
            model.addAttribute("userZm",sysUserCertificates);
            url="projectManager/companysDetail";
        }
        if (StringUtil.isNotBlank(sysUser.getDoBest())) {
            String mainFzFieldstr = getLxText(sysUser.getDoBest(), DictTypes.DOBEST.getType());
            model.addAttribute("strbest", mainFzFieldstr);
        }

        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");

        SupervisorFile supervisorFile = new SupervisorFile();
        supervisorFile.setProjectId(sysUser.getId());
        //supervisorFile.setType("101");
        supervisorFile = supervisorFileService.getPersonalImg(sysUser.getId());
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectListByLevelId("2");

        // 单位名称 // 单位性质  // 组织机构代码
        model.addAttribute("edulist", edulist);
        model.addAttribute("fileuser", supervisorFile);
        model.addAttribute("companyName", companyName);
        model.addAttribute("dwxz", dwxz);
        model.addAttribute("jgdm", jgdm);
        model.addAttribute("user", sysUser);
        //省
        model.addAttribute("provincelist", provincelist);
        //市
        model.addAttribute("citylist", citylist);
        return url;
    }


    @GetMapping(value = "tbFileDetail")
    public String tbFileDetail(SupplierProjectAcceptDTO dto, Model model) {
        SupervisorFileTemp supervisorFileTemp = new SupervisorFileTemp();
        supervisorFileTemp.setLinkId(dto.getSupAcceptId());
        List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(supervisorFileTemp);
        model.addAttribute("filelist", selectfile);
        return "projectManager/tbFileDetail";
    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:10:04 2021/3/31
     */
    @GetMapping(value = "/projectManager/acceptProjectDetail")
    public String acceptProjectDetail(SupplierProjectDTO supplierProjectDTO, Model model) {
        String supProjectId = supplierProjectDTO.getSupProjectId();

        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        SysUser sysUser = getSysUser();
        String auditStatus = sysUser.getAuditStatus();
        //001 供方 002 需方
        String gxType = sysUser.getGxType();
        String sourse = sysUser.getSource();
        // 001  002 组织
        String personType = sysUser.getPersonType();
        Boolean isTs = false;
        // 001 正中人员  002  项目生成 --审核之后变成003  003自行注册
        if ("001".equals(sourse)) {
            model.addAttribute("source", "n");
        } else {
            model.addAttribute("source", "w");
        }
        // 保证金比例
        List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.BZJBL.getType());
        if (typeListSsbl.size() > 0) {
            BaseDict bzjbl = typeListSsbl.get(0);
            String bzjper = bzjbl.getBadtLevel1();
            model.addAttribute("bzjper", bzjper);
        }
        // 根据项目类型 获取项目经理的集合
        String projectType = project.getProjectType();


        model.addAttribute("supProjectId", supProjectId);
        model.addAttribute("project", project);
        return "projectManager/acceptProjectDetail";
    }


    /**
     * @param request
     * @Author:zhaoyongke
     * @Description: 获取项目经理
     * @Date:14:21 2021/3/31
     */
    @GetMapping(value = "getXmjl")
    @ResponseBody
    public JsonUtil getXmjl(HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        // 外部的项目应接人
        SysUser sysUser = getSysUser();
        String source = sysUser.getSource();


        System.out.println("MMMMMMMMMMMMm");
        String xmjl = request.getParameter("xmjl");
        if (StringUtil.isBlank(xmjl)) {
            re.setFlag(false);
            re.setMsg("获取数据异常！！");
            return re;
        }
        try {
            if (xmjl.equals("jlManagerPerson")) {
                xmjl = "xmjl";
            }
            ;
            if (xmjl.equals("zxManagerPerson")) {
                xmjl = "zxxmjl";
            }
            ;
            if (xmjl.equals("jcManagerPerson")) {
                xmjl = "jcxmjl";
            }
            ;
            if (xmjl.equals("qtManagerPerson")) {
                xmjl = "qtxmjl";
            }
            ;
            List<SysUser> sysUsers = new ArrayList<>();
            SysUserDTO sysUserDTO = new SysUserDTO();
            sysUserDTO.setUserRole(xmjl);
            if ("001".equals(source)) {
                //正中内部的应接人(用户表都能维护了公司Id)
                sysUserDTO.setCompanyName(sysUser.getCompanyName());
            } else {
                String personType = sysUser.getPersonType();
                if ("001".equals(personType)) {
                    //外部个人
                    // 个人查询 没有维护公司的项目经理
                    sysUserDTO.setNotCompanyName("111");
                } else {
                    //外部组织
                    // 获取当前登陆人的单位信息
                    sysUserDTO.setCompanyName(sysUser.getCompanyName());
                }
            }

            sysUsers = sysUserService.getUserDicts(sysUserDTO);
            re.setFlag(true);
            re.setData(sysUsers);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("获取数据异常！！" + e.getMessage());
            return re;
        }
    }


    /**
     * @Author:zhaoyongke
     * @Description:项目详情
     * @Date:18:05 2021/3/22
     */
    @GetMapping(value = "/projectManager/projectDetail")
    public String projectDetail(SupplierProjectDTO supplierProjectDTO, Model model, HttpServletRequest request) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("admin") || subject.hasRole("gsgc") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")) {
            model.addAttribute("admin","admin");
        }

        String type = request.getParameter("type");
        // 外部單位发布的项目 x天无应接
        String fix = request.getParameter("fix");
        // 内部单位中标审核人
        String zbshr = request.getParameter("zbshr");
        String tjperson = request.getParameter("tjperson");
        String caseId = request.getParameter("caseId");
        if (StringUtil.isNotBlank(fix)) {
            model.addAttribute("fix", "1");
        }
        // 外部单位发布的项目--推荐确认
        String tjconfirm = request.getParameter("tjconfirm");
        if (StringUtil.isNotBlank(tjconfirm)) {
            model.addAttribute("tjconfirm", "1");
        }
        if (StringUtil.isNotBlank(caseId)) {
            // 无应接 提醒 修改提醒状态
            ProjectNotice projectNotice = projectNoticeServie.selectByPrimaryKey(caseId);
            projectNotice.setIsView("1");
            projectNoticeServie.updateByPrimaryKey(projectNotice);
            //从 消息中过来的 详情
            model.addAttribute("fromnotice", "1");
        }
        String contract = request.getParameter("contract");
        if ("s".equals(contract)) {
            model.addAttribute("contract", "s");
        }
        String projectId = supplierProjectDTO.getSupProjectId();
        SupplierProjectDTO supplierProjectDTO1 = new SupplierProjectDTO();
        supplierProjectDTO1.setSupProjectId(projectId);

        List<SupplierProjectDTO> supplierProjectDTOS = supplierProjectManagerService.selectProject(supplierProjectDTO1);
        String publishType = "";
        String userId = CommonUtil.getUserId();
        SupplierProjectDTO projectDTO = new SupplierProjectDTO();
        if (supplierProjectDTOS.size() > 0) {
            projectDTO = supplierProjectDTOS.get(0);
            String checkStatus = projectDTO.getCheckStatus();
            String status = projectDTO.getStatus();
            String publishBy = projectDTO.getPublishBy();
            String createBy = projectDTO.getCreateBy();
            publishType = projectDTO.getPublishType();
            String pubComType = projectDTO.getPubComType();
            String zbCompany = projectDTO.getZbCompany();
            String zbComType = projectDTO.getZbComType();
            // 中标人
            String zbBy = projectDTO.getZbBy();
            if(StringUtil.isNotBlank(zbBy)){
                String userId1 = CommonUtil.getUserId();
                if(userId1.equals(zbBy)){
                    model.addAttribute("zbperson","1");
                }

            }
            if ("001".equals(pubComType)) {
                BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(projectDTO.getPublishCompany());
                model.addAttribute("comName", baseCompany.getBcName());
            } else {
                SysUser sysUser = sysUserService.selectByPrimaryKey(projectDTO.getPublishCompany());
                model.addAttribute("comName", sysUser.getCompanyName());
            }
            //获取中标单位
            if("001".equals(zbComType)){
                BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(zbCompany);
                model.addAttribute("zbComName", baseCompany.getBcName());

            }else if("002".equals(zbComType)){
                SysUser sysUser = sysUserService.selectByPrimaryKey(zbCompany);
                model.addAttribute("zbComName", sysUser.getCompanyName());
            }
            if ("006".equals(status) && (userId.equals(publishBy) || userId.equals(createBy)) && ("1".equals(checkStatus) || "0".equals(checkStatus))) {
                //已经发布的项目  发布人和创建人 和审核人看到的最新修改过的项目
                //审核中---查询变更表
                SupplierProjectChangeDTO changeDTO = supplierProjectManagerChangeService.getChangeProject(projectDTO);
                model.addAttribute("project", changeDTO);
                //处理实施地点和人员地点要求
                getProjectPlaceChange(model, projectDTO.getSupProjectId(), changeDTO.getSupProjectChangeId());
                SupplierProjectDTO dicprodto = new SupplierProjectDTO();
                BeanUtil.copyNotNullBean(changeDTO, dicprodto);
                //处理字典
                getProjectDic(model, dicprodto);
                // 获取文件
                getFileModel(model, changeDTO.getSupProjectChangeId());

            } else {

                model.addAttribute("project", projectDTO);
                //处理实施地点和人员地点要求
                getProjectPlace(model, projectDTO);
                //处理字典
                getProjectDic(model, projectDTO);
                // 获取文件
                getFileModel(model, projectDTO.getSupProjectId());
            }
            // 实施比例
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.SSBL.getType());
            if (typeListSsbl.size() > 0) {
                BaseDict ssbl = typeListSsbl.get(0);
                String ssblper = ssbl.getBadtLevel1();
                model.addAttribute("ssblper", ssblper);
            }
        }else{
            model.addAttribute("message","该项目已删除");
            return "/error/message";
        }
        //收藏按钮展示
        ProjectCollect pc=new ProjectCollect();
        pc.setProjectId(projectId);
        pc.setCreateBy(userId);
        List<ProjectCollect> list=projectCollectService.selectCollect(pc);
        if(list!=null&&list.size()>0){
            model.addAttribute("collect","1");
        }else{
            model.addAttribute("collect","0");
        }
        String url = addModelDetail(model, projectDTO, type);
        // 内部项目推荐
        if (StringUtil.isNotBlank(zbshr)) {
            model.addAttribute("zbshr", "1");
            model.addAttribute("tjperson", tjperson);
            model.addAttribute("acceptview", "1");
            model.addAttribute("gxtype", "x");
        }
        // 内部项目 推荐中标审核人  通过列表 也能 显示 推荐 同意 或 不同意
        Example enb = new Example(ProjectNotice.class);
        Example.Criteria cnb = enb.createCriteria();
        cnb.andEqualTo("linkId", supplierProjectDTO.getSupProjectId());
        cnb.andEqualTo("sendTo", CommonUtil.getUserId());
        cnb.andEqualTo("noticeType", "107");
        List<ProjectNotice> projectNoticesnb = projectNoticeServie.selectByExample(enb);
        if(projectNoticesnb!=null){
            if(projectNoticesnb.size()>0){
                for (int i = 0; i <projectNoticesnb.size() ; i++) {
                    ProjectNotice notice = projectNoticesnb.get(i);
                    String tjPerson = notice.getTjPerson();
                    model.addAttribute("tjperson",tjPerson);
                }
            }
        }
        boolean istjperson = model.containsAttribute("tjperson");
        if(subject.hasRole("zbCheckPerson")  &&  istjperson){
            model.addAttribute("zbshr", "1");
            model.addAttribute("acceptview", "1");
            model.addAttribute("gxtype", "x");
        }

        // 外部发布的项目--推荐确认
        if (StringUtil.isNotBlank(tjconfirm)) {
            model.addAttribute("tjconfirm", "1");
            model.addAttribute("tjperson", tjperson);
        }
        // 外部发布的项目--推荐确认 ----外部查询项目查询推荐 解决 推荐按钮不能通过   项目列表 点击显示
        Example e = new Example(ProjectNotice.class);
        Example.Criteria c = e.createCriteria();
        c.andEqualTo("linkId", supplierProjectDTO.getSupProjectId());
        c.andEqualTo("sendTo", CommonUtil.getUserId());
        c.andEqualTo("noticeType", "105");
        List<ProjectNotice> projectNotices = projectNoticeServie.selectByExample(e);
        if(projectNotices!=null){
            if(projectNotices.size()>0){
                for (int i = 0; i <projectNotices.size() ; i++) {
                    ProjectNotice notice = projectNotices.get(i);
                    String tjPerson = notice.getTjPerson();
                    model.addAttribute("tjperson",tjPerson);
                    model.addAttribute("tjconfirm", "1");
                }
            }
        }
        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();
        model.addAttribute("comlistOwner", alstCompanyGs);
        return url;

    }

    /**
     * @param model
     * @param linkId
     * @Author:zhaoyongke
     * @Description: 获取文件
     * @Date:18:12 2021/4/9
     */
    public void getFileModel(Model model, String linkId) {

        if(StringUtils.isNotBlank(linkId)){
            // 获取文件
            SupervisorFileTemp tempfile = new SupervisorFileTemp();
            tempfile.setLinkId(linkId);
            List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(tempfile);
            Boolean zbsmfile = false;
            Boolean zbfile = false;
            Boolean tbfile = false;
            Boolean htfile = false;
            Boolean htsmfile = false;
            Boolean htzbtzs = false;
            // 311 上传项目招标文件说明文件

            for (int i = 0; i < selectfile.size(); i++) {
                SupervisorFileTemp supervisorFileTemp = selectfile.get(i);
                String type1 = supervisorFileTemp.getType();
                if ("311".equals(type1)) {
                    zbsmfile = true;
                    model.addAttribute("zbsmfile", zbsmfile);
                }
                if ("312".equals(type1)) {
                    zbfile = true;
                    model.addAttribute("zbfile", zbfile);
                }
                if ("313".equals(type1)) {
                    tbfile = true;
                    model.addAttribute("tbfile", tbfile);
                }
                if ("314".equals(type1)) {
                    htfile = true;
                    model.addAttribute("htfile", htfile);
                }
                if ("315".equals(type1)) {
                    //上传合同说明文件
                    htsmfile = true;
                    model.addAttribute("htsmfile", htsmfile);
                }
                if ("316".equals(type1)) {
                    //上传中标通知书
                    htzbtzs = true;
                    model.addAttribute("htzbtzs", htzbtzs);
                }

            }
            model.addAttribute("filelist", selectfile);
        }


    }

    /**
     * @param model
     * @param projectDTO
     * @param type
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:28 2021/3/30
     */
    public String addModelDetail(Model model, SupplierProjectDTO projectDTO, String type) {
        String editurl = "projectManager/projectDetailEditNb";
        String detailurl = "projectManager/projectDetailXfNb";
        SysUser sysUser = getSysUser();
        String auditStatus = sysUser.getAuditStatus();
        String createBy = projectDTO.getCreateBy();
        String publishBy = projectDTO.getPublishBy() + "";
        //到了截至日期就不可以应接
        Date currdate = new Date();
        if(!"".equals(projectDTO.getZbEndDate()) || projectDTO.getZbEndDate() == null){
            Date zbEndDate = DateUtil.parseDate(projectDTO.getZbEndDate(), "yyyy-MM-dd HH:mm");
            if(currdate.after(zbEndDate)){
                model.addAttribute("messages","招标截止日期已到不可以应接该项目");
            }
            if(currdate.before(zbEndDate)){
                // 不到招标截止时间 不能选择 中标人（不显示选择按钮）
                model.addAttribute("tbbut","0");

            }
        }
        //001 供方 002 需方
        String gxType = sysUser.getGxType();
        String sourse = sysUser.getSource();
        String zbStatus=projectDTO.getZbStatus();
        model.addAttribute("zbStatus",zbStatus);
        // 001  002 组织
        String personType = sysUser.getPersonType();
        Boolean isTs = false;
        // 001 正中人员  002  项目生成 --审核之后变成003  003自行注册
        if ("001".equals(sourse)) {
            model.addAttribute("source", "n");
        } else {
            model.addAttribute("source", "w");
            if (!"1".equals(auditStatus)) {
                isTs = true;
                model.addAttribute("message", "暂时无法应接项目，需要完善信息才可以应接项目");
            }
        }

        if ("001".equals(gxType)) {
            //判断是否有迎接资格  外部注册的供方个人 （正中内部和供方组织不需要校验）
            if ("001".equals(personType) && !isTs) {
                JsonUtil acceptsjson = isAcceptZg(projectDTO, sysUser);
                if (!acceptsjson.isFlag() && !isTs) {
                    model.addAttribute("message", acceptsjson.getMsg());
                }
            }
            model.addAttribute("gxtype", "g");
            SupplierProjectAccept accept = new SupplierProjectAccept();
            accept.setAcceptBy(CommonUtil.getUserId());
            accept.setSupProjectId(projectDTO.getSupProjectId());
            int acceptcount = supplierProjectAcceptService.selectCount(accept);
            if (acceptcount > 0) {
                model.addAttribute("acceptview", "1");
            }

        } else if ("002".equals(gxType)) {
            // 控制综合对比
            // 判断是否有应接记录
            SupplierProjectAccept accept = new SupplierProjectAccept();
            accept.setSupProjectId(projectDTO.getSupProjectId());
            int acceptcount = supplierProjectAcceptService.selectCount(accept);
            if (acceptcount > 0 && (CommonUtil.getUserId().equals(createBy) || CommonUtil.getUserId().equals(publishBy))) {
                model.addAttribute("acceptview", "1");
            }
            model.addAttribute("gxtype", "x");
        }
        if (CommonUtil.getUserId().equals(createBy) || CommonUtil.getUserId().equals(publishBy)) {
            model.addAttribute("myself", "1");
        }
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        model.addAttribute("checkShapeList", checkShapeList);
        if ("001".equals(projectDTO.getPublishType())) {
            //正中内部发布
            if ("m".equals(type)) {
                // 编辑页面
                //如果项目oaId不为空,查询oa项目信息保存如model
                if(StringUtils.isNotBlank(projectDTO.getOaId())){
                    JSONObject paraObj = new JSONObject();
                    paraObj.put("dataid",projectDTO.getOaId());
                    try{
                        OaData oaData1 = new OaData();
                        oaData1.setOaId(projectDTO.getOaId());
                        List<OaData> oaData = oaDataService.select(oaData1);
                        if(null != oaData && CollectionUtil.isNotEmpty(oaData)){
                            OaData oaReDataDTO = oaData.get(0);
                            model.addAttribute("oaProjInfo", JSON.toJSONString(oaReDataDTO));
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            editurl = "projectManager/projectDetailEditNb";
            detailurl = "projectManager/projectDetailXfNb";
        } else {
            editurl = "projectManager/projectDetailEditWb";
            detailurl = "projectManager/projectDetailXfWb";

        }
        if ("m".equals(type)) {
            // 编辑页面
            return editurl;
        } else {
            //详情页面
            return detailurl;
        }

    }

    /**
     * @param projectDTO
     * @param user
     * @Author:zhaoyongke
     * @Description: 外部的供方个人需要校验 （正中内部和供方组织不需要校验）
     * @Date:18:18 2021/3/30
     */
    public JsonUtil isAcceptZg(SupplierProjectDTO projectDTO, SysUser user) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(true);
        //需要出差
        String mainFzTrip = projectDTO.getMainFzTrip();
        //性别
        String mainFzSex = projectDTO.getMainFzSex();
        // 学历
        String mainFzXl = projectDTO.getMainFzXl();
        //擅长领域
        String mainFzField = projectDTO.getMainFzField();
        // 人员地区要求
        List<ProjectPlaceDTO> projectPlacedtos = projectDTO.getPersonPlacedtos();
        String sex = user.getSex();
        String doBest = user.getDoBest();
        String bussTravel = user.getBussTravel();
        String education = user.getEducation();
        String province = user.getProvince();
        String city = user.getCity();
        String postAddress = user.getPostAddress();
        String source = user.getSource();
        String personType = user.getPersonType();
        String gxType = user.getGxType();

        //性别
        if (StringUtil.isNotBlank(mainFzSex)) {
            if (!mainFzSex.equals(sex)) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("不符合发布的人员性别要求，无法应接本项目");
                return jsonUtil;
            }
        }
        //学历
        if (StringUtil.isNotBlank(mainFzXl)) {

            if("001".equals(source)  &&  "001".equals(personType)  && "001".equals(gxType) ){
                // 20210907 修改
                Boolean xlcheck=false;
                // 查询 学历表
                SysUserEducation firstEducation = new SysUserEducation();
                firstEducation.setSuId(user.getId());
                List<SysUserEducation> userEducationList = userEducationService.select(firstEducation);
                if(userEducationList!=null ){
                    if(userEducationList.size()>0){
                        for (int i = 0; i < userEducationList.size(); i++) {
                            SysUserEducation sysUserEducation = userEducationList.get(i);
                            String suenName = sysUserEducation.getSuenName();
                            if(StringUtil.isNotBlank(suenName)  && StringUtil.isNotBlank(suenName.replace("请选择", ""))){
                                int  xl = Integer.valueOf(suenName);
                                int aDouble = Integer.valueOf(mainFzXl);
                                if(aDouble< xl  || aDouble== xl   ){
                                    xlcheck=true;
                                    break;
                                }
                            }
                        }
                    }

                }

                if(!xlcheck){
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("不符合发布的人员学历要求，无法应接本项目");
                    return jsonUtil;
                }

            }else{
                if(StringUtil.isBlank(education)){
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("不符合发布的人员学历要求，无法应接本项目");
                    return jsonUtil;
                }
                Integer integerxl = Integer.valueOf(mainFzXl);
                Integer integeredtu = Integer.valueOf(education);
                if (integerxl>integeredtu) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("不符合发布的人员学历要求，无法应接本项目");
                    return jsonUtil;

                }
            }

        }
        // 是否需要出差
        if ("1".equals(mainFzTrip)) {
            if ("0".equals(bussTravel)) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("不符合发布的人员出差要求，无法应接本项目");
                return jsonUtil;
            }
        }
        //擅长领域判断
        if (StringUtil.isNotBlank(mainFzField)) {
            //地区和擅长领域
            if (StringUtil.isBlank(doBest)) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("不符合发布的人员擅长领域要求，无法应接本项目");
                return jsonUtil;
            } else {
                Boolean isfind = false;
                String[] split = doBest.split(",");
                String[] splitprject = mainFzField.split(",");
                for (int i = 0; i < split.length; i++) {
                    String best = split[i];
                    if (Arrays.asList(splitprject).contains(best)) {
                        isfind = true;
                        break;

                    }
                }
                if (!isfind) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("不符合发布的人员擅长领域要求，无法应接本项目");
                    return jsonUtil;
                }

            }
        }
        // 人员地区判断
        //projectPlacedtos
        if (projectPlacedtos != null && projectPlacedtos.size() > 0) {
            Boolean istgDq = false;
            for (int i = 0; i < projectPlacedtos.size(); i++) {
                ProjectPlaceDTO placeDTO = projectPlacedtos.get(i);
                String provincePro = placeDTO.getProvince();
                String cityPro = placeDTO.getCity();

                if("001".equals(source)  &&  "001".equals(personType)  && "001".equals(gxType) ){
                    // 正中  个人  供方  取 通讯地址
                    if(StringUtil.isNotBlank(postAddress)) {
                        String protr = "";
                        // 获取省的 字符
                        SysRegion sysRegion = new SysRegion();
                        sysRegion.setCode(provincePro);
                        List<SysRegion> select = sysRegionService.select(sysRegion);
                        if (select != null) {
                            if (select.size() > 0) {
                                SysRegion sysRegion1 = select.get(0);
                                protr = sysRegion1.getName().replaceAll("省", "");
                            }
                        }
                        if (StringUtil.isBlank(cityPro)) {
                            //要求的市为空
                            if (postAddress.indexOf(protr) > -1) {
                                istgDq = true;
                                break;
                            }

                        } else {
                            String citystr = "";
                            SysRegion sysRegioncity = new SysRegion();
                            sysRegioncity.setCode(cityPro);
                            List<SysRegion> selectcity = sysRegionService.select(sysRegioncity);
                            if (selectcity != null) {
                                if (selectcity.size() > 0) {
                                    SysRegion sysRegion1 = selectcity.get(0);
                                    citystr = sysRegion1.getName().replaceAll("市", "");
                                }

                            }
                            if (postAddress.indexOf(citystr) > -1) {
                                istgDq = true;
                                break;
                            }

                        }

                    }



                }else{
                    if (provincePro.equals(province)) {
                        if (StringUtil.isBlank(cityPro)) {
                            istgDq = true;
                            break;
                        } else {
                            if (cityPro.equals(city)) {
                                istgDq = true;
                                break;
                            }

                        }

                    }

                }


            }
            if (!istgDq) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("不符合发布的人员地区要求，无法应接本项目");
                return jsonUtil;
            }

        }

        return jsonUtil;

    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:14:29 2021/3/24
     */
    public void getProjectPlace(Model model, SupplierProjectDTO projectDTO) {
        // 实施地点
        ProjectPlaceDTO dto = new ProjectPlaceDTO();
        dto.setSupProjectId(projectDTO.getSupProjectId());
        dto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(dto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist);
        }
        projectDTO.setProjectPlacedtos(listpalce);
        model.addAttribute("listpalce", listpalce);
        // 人员地点
        ProjectPlaceDTO dtopersonplace = new ProjectPlaceDTO();
        dtopersonplace.setSupProjectId(projectDTO.getSupProjectId());
        dtopersonplace.setType("002");
        List<ProjectPlaceDTO> listPersonPalce = projectPlaceService.selectPlace(dtopersonplace);
        for (int i = 0; i < listPersonPalce.size(); i++) {
            String province = listPersonPalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listPersonPalce.get(i).setCitys(citylist);
            String city = listPersonPalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listPersonPalce.get(i).setCountys(countylist);
        }
        projectDTO.setPersonPlacedtos(listPersonPalce);
        model.addAttribute("listperpalce", listPersonPalce);


    }

    /**
     * @param model
     * @param projectId
     * @param proChangeId
     * @Author:zhaoyongke
     * @Description: 获取变更后的地点
     * @Date:15:43 2021/3/29
     */
    public void getProjectPlaceChange(Model model, String projectId, String proChangeId) {
        // 实施地点
        ProjectPlaceChangeDTO dto = new ProjectPlaceChangeDTO();
        dto.setSupProjectId(projectId);
        dto.setSupProjectChangeId(proChangeId);
        dto.setType("001");
        List<ProjectPlaceChangeDTO> listpalce = projectPlaceChangeService.selectPlace(dto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist);
        }
        model.addAttribute("listpalce", listpalce);
        // 人员地点
        ProjectPlaceChangeDTO dtopersonplace = new ProjectPlaceChangeDTO();
        dtopersonplace.setSupProjectId(projectId);
        dtopersonplace.setSupProjectChangeId(proChangeId);
        dtopersonplace.setType("002");
        List<ProjectPlaceChangeDTO> listPersonPalce = projectPlaceChangeService.selectPlace(dtopersonplace);
        for (int i = 0; i < listPersonPalce.size(); i++) {
            String province = listPersonPalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listPersonPalce.get(i).setCitys(citylist);
            String city = listPersonPalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listPersonPalce.get(i).setCountys(countylist);
        }
        model.addAttribute("listperpalce", listPersonPalce);
    }


    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:14:25 2021/3/24
     */
    public void getProjectDic(Model model, SupplierProjectDTO dto) {
        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        /*行业类型*/
        List<BaseDict> hyTypeList = DictUtil.getDictByType(DictTypes.INDUSTRY);
        //擅长领域
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");

        if (StringUtil.isNotBlank(dto.getMainFzField())) {
            String mainFzFieldstr = getLxText(dto.getMainFzField(), DictTypes.DOBEST.getType());
            model.addAttribute("strbest", mainFzFieldstr);
        }
        if (StringUtil.isNotBlank(dto.getProjectType())) {
            //項目類型
            String proTypestr = getLxText(dto.getProjectType(), DictTypes.YW_TYPE.getType());
            model.addAttribute("strprojecttype", proTypestr);
        }
        if (StringUtil.isNotBlank(dto.getHyType())) {
            //行业类型
            String hyTypestr = getLxText(dto.getHyType(), DictTypes.INDUSTRY.getType());
            model.addAttribute("hyTypestr", hyTypestr);
        }
        if (StringUtil.isNotBlank(dto.getSupervisorWay())){
            // 监理形式
            String supervisorWay = getLxText(dto.getSupervisorWay(),DictTypes.CHECK_SHAPE.getType());
            model.addAttribute("supervisorWay", supervisorWay);
        }
        // 市
        List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(dto.getHtSignProvince());
        // 县
        List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(dto.getHtSignCity());


        model.addAttribute("citylist", citylist);
        model.addAttribute("countylist", countylist);
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("hytypelist", hyTypeList);
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("edulist", edulist);
        model.addAttribute("doBestList", doBestList);
    }

    /**
     * @param field
     * @param typecode
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:04 2021/3/23
     */
    public String getLxText(String field, String typecode) {
        List<BaseDict> codeList = baseDictService.selectByTypeCode(typecode);
        HashMap<String, String> mapbest = new HashMap();
        for (int i = 0; i < codeList.size(); i++) {
            mapbest.put(codeList.get(i).getBadtCode(), codeList.get(i).getBadtName());
        }
        //擅长领域
        List<String> dobest = StringUtil.split(field);
        List<String> best = new ArrayList<>();
        for (int i = 0; i < dobest.size(); i++) {
            String s = dobest.get(i);
            String scname = mapbest.get(s);
            best.add(scname);
        }
        String strbest = best.toString().replaceAll("\\[", "").replaceAll("\\]", "");
        return strbest;

    }

    /**
     * @param request
     * @Author:zhaoyongke
     * @Description:项目发布
     * @Date:11:48 2021/3/15
     */
    @GetMapping(value = "projectPush")
    @RequiresPermissions("supplier:push")
    public String firstIprojectPushndex(Model model, HttpServletRequest request) {
        //通过身份 判断是否有资格发布信息
        String strurl = isHashPermessionFb(model);
        if (StringUtil.isNotBlank(strurl)) {
            return strurl;
        }
        SysUser user = getSysUser();
        String company = user.getCompanyName();
        String source = user.getSource();
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        /*行业类型*/
        List<BaseDict> hyTypeList = DictUtil.getDictByType(DictTypes.INDUSTRY);
        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");
        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        model.addAttribute("comlistOwner", alstCompanyGs);
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 实施比例
        List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.SSBL.getType());
        if (typeListSsbl.size() > 0) {
            BaseDict ssbl = typeListSsbl.get(0);
            String ssblper = ssbl.getBadtLevel1();
            model.addAttribute("ssblper", ssblper);
        }
        //擅长领域
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("hytypelist", hyTypeList);
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("edulist", edulist);
        model.addAttribute("doBestList", doBestList);
        model.addAttribute("user", user);
        model.addAttribute("checkShapeList", checkShapeList);


        // 来源  001 正中人员  002  项目生成 --审核之后变成003  003自行注册
        if ("001".equals(source)) {
            if (StringUtil.isNotBlank(company)) {
                BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(company);
                model.addAttribute("baseCompany", baseCompany);
            }
            return "projectManager/projectPush";
        } else {
            //注册需方
            return "projectManager/projectPushWb";
        }
    }

    public SysUser getSysUser() {
        String userId = CommonUtil.getUserId();
        SysUser user = sysUserService.selectByPrimaryKey(userId);
        return user;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:删除项目
     * @Date:16:49 2021/3/24
     */
    @PostMapping(value = "/projectManager/deletePro")
    @ResponseBody
    public JsonUtil deletePro(SupplierProjectDTO dto) {
        String supProjectId = dto.getSupProjectId();
        if (StringUtils.isEmpty(supProjectId)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil re = new JsonUtil();
        try {
            //已保存、已撤销、已驳回状态的项目
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
            String createBy = project.getCreateBy();
            String publishBy = project.getPublishBy();
            String userId = CommonUtil.getUserId();
            String status = project.getStatus();
            if(!"001".equals(status)  && !"003".equals(status) && !"005".equals(status) ){
                return JsonUtil.error("失败：只能操作已保存、已撤销、已驳回状态的项目");
            }
            if (!userId.equals(publishBy) &&  !userId.equals(createBy)) {
                return JsonUtil.error("失败：只允许项目发布人删除！");
            }
            // 删除文件
            SupervisorFileTemp supervisorFileTemp = new SupervisorFileTemp();
            supervisorFileTemp.setLinkId(supProjectId);
            supervisorFileTempService.delete(supervisorFileTemp);
            // 删除地点
            ProjectPlace placeDTO = new ProjectPlace();
            placeDTO.setSupProjectId(supProjectId);
            projectPlaceService.delete(placeDTO);
            // 删除项目
            supplierProjectManagerService.deleteByPrimaryKey(supProjectId);
            re.setFlag(true);
            re.setMsg("操作成功");

        } catch (Exception e) {
            re.setMsg("操作失败：" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:18 2021/3/23
     */
    public String isHashPermessionFb(Model model) {
        String errourl = "";
/*        平台拥有方的市场人员和注册需方组织可在此处发布项目信息，
        如果是平台拥有方的市场人员则直接进入到发布页面，
        如果是注册需方组织则需要判断单位性质，
        单位性质为机关，则直接直接进入到发布页面，单位性质为企业，判断是否完善个人信息*/
        String userId = CommonUtil.getUserId();
        SysUser user = sysUserService.selectByPrimaryKey(userId);
        String gxType = user.getGxType();
        String source = user.getSource();
        //单位性质
        String companyType = user.getCompanyType();// 001 企业  002 机关
        if (StringUtil.isBlank(source)) {
            model.addAttribute("message", "请维护用户来源");
            model.addAttribute("messtype", "1");
            errourl = "/error/message";
            return errourl;
        }
        if (StringUtil.isBlank(gxType)) {
            model.addAttribute("message", "请维护供需类型");
            model.addAttribute("messtype", "1");
            errourl = "/error/message";
            return errourl;
        }
        // 001 供方 002 需方
        if (!"002".equals(gxType)) {
            model.addAttribute("message", "需方才有发布资格");
            model.addAttribute("messtype", "1");
            errourl = "/error/message";
            return errourl;
        } else {
            // 001 正中人员  002  项目生成 --审核之后变成003  003自行注册
            //需方
            if ("001".equals(source)) {
                if (!com.qili.core.shiro.Principal.hasRole("scry")) {
                    model.addAttribute("message", "平台拥有方的市场人员才有发布资格");
                    model.addAttribute("messtype", "1");
                    errourl = "/error/message";
                    return errourl;
                }
            } else {
                if (StringUtil.isBlank(companyType)) {
                    model.addAttribute("message", "请维护单位性质");
                    model.addAttribute("messtype", "2");
                    errourl = "/error/message";
                    return errourl;
                }
                //单位性质为机关，则直接直接进入到发布页面，单位性质为企业，判断是否完善个人信息  001 企业  002 机关
                if ("001".equals(companyType)) {
                    String austatus = user.getAuditStatus();
                    if (!"1".equals(austatus)) {
                        model.addAttribute("message", "没有发布资格：企业信息不完善，请先去完善信息，完善资料且经过系统管理员审核通过后，才可以进入到发布页面");
                        model.addAttribute("messtype", "2");
                        errourl = "/error/message";
                        return errourl;
                    }
                }
            }

        }

        return errourl;

    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:  首页--项目列表
     * @Date:16:45 2021/3/13
     */
    @ApiOperation(value = "/projectManager/showProjectList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/projectManager/showProjectList")
    @ResponseBody
    public ReType showProjectList(SupplierProjectDTO project, Model model, String page, String limit) {
        //已发布
//        project.setStatus("006");
//        String projectName = project.getProjectName();
//        OperQueryRecord record = new OperQueryRecord();
//        if(StringUtils.isNotBlank(projectName)){
//            record.setKeyword(projectName);
//            operQueryRecordService.insertSelective(record);
//        }
        // 判断当前登录人 是内部 还是外部
//        SysUser sysUser = getSysUser();
//        String source = sysUser.getSource();
//        String gxType=sysUser.getGxType();
//        String personType=sysUser.getPersonType();
//        Subject subject = SecurityUtils.getSubject();
//        if (subject.hasRole("admin") || subject.hasRole("gsgc") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")) {
//
//        }else{
//            if(!"001".equals(source)){
//                //外部人员 只能查看正中内部的  为公开状态的
//                project.setViewType("11111");
//            }
//            if(StringUtils.isNotBlank(gxType)&&StringUtils.isNotBlank(personType)&&"001".equals(gxType)&&"002".equals(personType)){
//                project.setPublishTypes("001");
//            }
//        }
//        if(subject.hasRole("zbCheckPerson")){
//            // 中标审核人 可以看到 已过时间的
//            project.setZbcheckview("1");
//        }else{
//            project.setZbcheckview("0");
//        }



        //已发布
        project.setStatus("006");
        String projectName = project.getProjectName();
        OperQueryRecord record = new OperQueryRecord();
        if(StringUtils.isNotBlank(projectName)){
            record.setKeyword(projectName);
            operQueryRecordService.insertSelective(record);
        }
        // 判断当前登录人 是内部 还是外部
        SysUser sysUser = getSysUser();
        String source = sysUser.getSource();
        String gxType=sysUser.getGxType();
        String personType=sysUser.getPersonType();
        Subject subject = SecurityUtils.getSubject();
        /**
         * 2022年3月18日17:08:25
         *
         * 查看所有项目：
         *  系统管理员、市场部经理、供方合同负责人
         *
         * 按照部门区分：
         *  市场人员、发布审核人、中标审核人、供需经理
         *  scry   pucheckper  zbCheckPerson  gxjl
         */
        if (subject.hasRole("admin") || subject.hasRole("gfhtperson") ||subject.hasRole("gsgc")) {


        }else if ( subject.hasRole("scry") || subject.hasRole("gxjl") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")){
            // 获取当前登录人的用户信息
            SysUser user = sysUserService.selectByPrimaryKey(sysUser.getId());
            // 根据公司查询
            project.setCompanyName(user.getCompanyName());
            // 根据部门查询
            // 获取发布人的部门 【市场一部 || 分支管理部】
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setSuId(user.getId());
            nowWork.setIfNow("1");
            SysUserWorkExperience experience =null;
            List<SysUserWorkExperience> selectlist = userWorkExperienceService.select(nowWork);
            if(!CollectionUtils.isEmpty(selectlist)){
                experience=selectlist.get(0);
                project.setDeptName(experience.getDeptCode());
            }else{
                project.setDeptName("1111");
            }
            if(subject.hasRole("gxjl")){
                project.setDestatus("001");
                project.setStatus(null);
            }
        } else if(subject.hasRole("scbjl")  ){
            // 2021 1111 市场部经理 能查看到 所有的  scbjl
            project.setDestatus("001");
            project.setStatus(null);
        }else{
            if(!"001".equals(source)){
                //外部人员 只能查看正中内部的  为公开状态的
                project.setViewType("11111");
            }
            if(StringUtils.isNotBlank(gxType)&&StringUtils.isNotBlank(personType)&&"001".equals(gxType)&&"002".equals(personType)){
                project.setPublishTypes("001");
            }
        }
        if(subject.hasRole("zbCheckPerson")  ||  subject.hasRole("scbjl")  ||  subject.hasRole("gxjl")  ){
            // 中标审核人 可以看到 已过时间的
            project.setZbcheckview("1");
        }else{
            project.setZbcheckview("0");
        }
        ReType re = supplierProjectManagerService.show(project, Integer.valueOf(page), Integer.valueOf(limit));
        return re;

    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:项目列表  項目中心 -项目列表
     * @Date:18:16 2021/3/25
     */
    @ApiOperation(value = "/projectManager/showProjectListLb", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/projectManager/showProjectListLb")
    @ResponseBody
    public ReType showProjectListLb(SupplierProjectDTO project, Model model, String page, String limit) {
        //已发布
        project.setStatus("006");
        String projectName = project.getProjectName();
        if (StringUtil.isNotBlank(project.getProvince()) || StringUtil.isNotBlank(project.getCity()) || StringUtil.isNotBlank(project.getCounty())) {
            project.setQueryPlace("1");
        } else {
            project.setQueryPlace("");
        }
        // 判断当前登录人 是内部 还是外部
        SysUser sysUser = getSysUser();
        String source = sysUser.getSource();
        String gxType=sysUser.getGxType();
        String personType=sysUser.getPersonType();
        Subject subject = SecurityUtils.getSubject();
        /**
         * 2022年3月18日17:08:25
         *
         * 查看所有项目：
         *  系统管理员、市场部经理、供方合同负责人
         *
         * 按照部门区分：
         *  市场人员、发布审核人、中标审核人、供需经理
         *  scry   pucheckper  zbCheckPerson  gxjl
         */
        if (subject.hasRole("admin") || subject.hasRole("gfhtperson") ||subject.hasRole("gsgc")) {


        }else if ( subject.hasRole("scry") || subject.hasRole("gxjl") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")){
            // 获取当前登录人的用户信息
            SysUser user = sysUserService.selectByPrimaryKey(sysUser.getId());
            // 根据公司查询
            project.setCompanyName(user.getCompanyName());
            // 根据部门查询
            // 获取发布人的部门 【市场一部 || 分支管理部】
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setSuId(user.getId());
            nowWork.setIfNow("1");
            SysUserWorkExperience experience =null;
            List<SysUserWorkExperience> selectlist = userWorkExperienceService.select(nowWork);
            if(!CollectionUtils.isEmpty(selectlist)){
                experience=selectlist.get(0);
                project.setDeptName(experience.getDeptCode());
            }else{
                project.setDeptName("1111");
            }
            // 供需经理
            if(subject.hasRole("gxjl")){
                project.setDestatus("001");
                project.setStatus(null);
            }
        } else if(subject.hasRole("scbjl")   ){
            // 2021 1111 市场部经理 能查看到 所有的  scbjl
            project.setDestatus("001");
            project.setStatus(null);
        }else{
            if(!"001".equals(source)){
                //外部人员 只能查看正中内部的  为公开状态的
                project.setViewType("11111");
            }
            if(StringUtils.isNotBlank(gxType)&&StringUtils.isNotBlank(personType)&&"001".equals(gxType)&&"002".equals(personType)){
                project.setPublishTypes("001");
            }
        }
        if(subject.hasRole("zbCheckPerson")  ||  subject.hasRole("scbjl") ||  subject.hasRole("gxjl")   ){
            // 中标审核人 可以看到 已过时间的
            project.setZbcheckview("1");
        }else{
            project.setZbcheckview("0");
        }
        ReType re = supplierProjectManagerService.show(project, Integer.valueOf(page), Integer.valueOf(limit));
        return re;

    }

    /**
     * @param supplierProjectDTO
     * @Author:zhaoyongke
     * @Description: 保存项目
     * @Date:17:08 2021/3/22
     */
    @RequestMapping("/projectManager/addSave")
    @ResponseBody
    public JsonUtil addSave(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                if (StringUtil.isNotBlank(supplierProjectDTO.getSupProjectId())) {
                    //删除原来的
                    supplierProjectManagerService.deleteByPrimaryKey(supplierProjectDTO.getSupProjectId());
                    ProjectPlace placeDTO = new ProjectPlace();
                    placeDTO.setSupProjectId(supplierProjectDTO.getSupProjectId());
                    projectPlaceService.delete(placeDTO);
                }
                if ("002".equals(supplierProjectDTO.getStatus())) {
                    // 验证提交供需项目未对招标时间是否晚于当前时间做校验
                    Date currdate = new Date();
                    Date zbEndDate = DateUtil.parseDate(supplierProjectDTO.getZbEndDate(), "yyyy-MM-dd HH:mm");
                    if(currdate.after(zbEndDate)){
                        return JsonUtil.error("招标截止时间应晚于当前时间！！");
                    }
                }
                //--校验是否重复
                SupplierProject pro = new SupplierProject();
                pro.setProjectName(supplierProjectDTO.getProjectName().trim());
                int countp = supplierProjectManagerService.selectCount(pro);
                if (countp > 0) {
                    return JsonUtil.error("项目名称不允许重复！！");
//                    Integer ordernum = supplierProjectManagerService.selectMaxOrderByPro()+1;
//                    NumberFormat formatter = new DecimalFormat("000");
//                    String AsOrderNum = formatter.format(ordernum);

//                    supplierProjectDTO.setOrderNum(AsOrderNum);
                }else{
                    supplierProjectDTO.setOrderNum("");
                }
                //(1)保存基本信息
                SupplierProject supProject = addProject(supplierProjectDTO);
                //（2） 保存实施地点
                List<ProjectPlaceDTO> projectPlacedtos = supplierProjectDTO.getProjectPlacedtos();
                if(CollectionUtils.isEmpty(projectPlacedtos)){
                    return JsonUtil.error("实施地点校验失败！！");
                }
                supplierProjectManagerService.addPalce(supplierProjectDTO, supProject);
                //（3）保存人员地点
                supplierProjectManagerService.addPersonPalce(supplierProjectDTO, supProject);
                //保存文件
                List<String> tempFormFileIds = supplierProjectDTO.getTempFormFileIds();
                String  size="0";
                if(!CollectionUtils.isEmpty(tempFormFileIds)){
                    size=tempFormFileIds.size()+"";

                }
                String text="111111111saveadd方法保存之前tempFormFileIds"+size;
                supervisorFileTempService.insertTolalLog("ADDSuTemp",text,supProject.getSupProjectId());

                if(tempFormFileIds != null){
                    for (int i = 0; i < tempFormFileIds.size(); i++) {
                        String tempId = tempFormFileIds.get(i);
                        SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(tempId);
                        supervisorFileTemp.setLinkId(supProject.getSupProjectId());
                        supervisorFileTempService.updateByPrimaryKey(supervisorFileTemp);
                        SysLog sysLog = new SysLog();
                        sysLog.setCreateTime(new Date());
                        sysLog.setType("ADDSuTemp");
                        sysLog.setText("saveadd方法=====");
                        sysLog.setParam(tempFormFileIds.size()+"页面文件数量"+supervisorFileTemp.toString());
                        sysLog.setIp(supProject.getSupProjectId());
                        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
                        CurrentUser currentUser = Principal.getCurrentUse();
                        sysLog.setUserName(currentUser.getUsername());
                        sysLogMapper.insert(sysLog);
                    }
                }

                String aftertext="1111111111111111saveadd方法保存之后tempFormFileIds"+size;
                supervisorFileTempService.insertTolalLog("ADDSuTemp",aftertext,supProject.getSupProjectId());

                if ("002".equals(supProject.getStatus())) {
                    // 发送消息
                    saveSendNoticeAffirCase(supProject);
                }
                //保存oa项目信息:
                /*if(StringUtils.isNotBlank(supplierProjectDTO.getOaId())){
                    saveOrUpdateOaProject(supplierProjectDTO.getOaId());
                }*/
                re.setFlag(true);
                re.setData(supProject.getSupProjectId());
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }

    }


/*
    private void saveOrUpdateOaProject(String oaProjectId){
        try {
            OaData oaData = new OaData();
            oaData.setOaId(oaProjectId);
            List<OaData> list = oaDataService.select(oaData);
            if(list != null){
                if(CollectionUtil.isNotEmpty(list)){
                    OaData oaData1 = list.get(0);
                    if(oaData1 != null){
                        oaDataService.updateByPrimaryKeySelective(oaData1);
                    }else{
                        oaDataService.insertSelective(oaData1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    /**
     * @param supplierProjectDTO
     * @Author:zhaoyongke
     * @Description: 撤销应接
     * @Date:18:27 2021/3/27
     */
    @RequestMapping("/projectManager/updateCxAccept")
    @ResponseBody
    public JsonUtil updateCxAccept(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                String supProjectId = supplierProjectDTO.getSupProjectId();
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
                //到了截至日期不可以撤销应接
                Date currdate = new Date();
                Date zbEndDate = DateUtil.parseDate(project.getZbEndDate(), "yyyy-MM-dd HH:mm");
                if(currdate.after(zbEndDate)){
                    re.setMsg("招标截止日期已到不可以撤销应接");
                    re.setFlag(false);
                    return re;
                }
                if ("004".equals(project.getStatus())) {
                    re.setFlag(false);
                    re.setMsg("项目已结束，不能撤销应接");
                    return re;
                }
                SupplierProjectAccept accept = new SupplierProjectAccept();
                accept.setSupProjectId(supProjectId);
                accept.setAcceptBy(CommonUtil.getUserId());
                List<SupplierProjectAccept> select = supplierProjectAcceptService.select(accept);
                for (int i = 0; i < select.size(); i++) {
                    // 刪除临时文件
                    SupervisorFileTemp supervisorFileTemp = new SupervisorFileTemp();
                    supervisorFileTemp.setLinkId(select.get(i).getSupAcceptId());
                    supervisorFileTempService.delete(supervisorFileTemp);
                    // 删除应接记录
                    supplierProjectAcceptService.deleteByPrimaryKey(select.get(i).getSupAcceptId());
                }
                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }

    }


    /**
     * @param supplierProjectDTO
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:27 2021/3/27
     */
    @RequestMapping("/projectManager/updateStatus")
    @ResponseBody
    public JsonUtil updateStatus(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                String supProjectId = supplierProjectDTO.getSupProjectId();
                SupplierProjectAccept accept = new SupplierProjectAccept();
                accept.setSupProjectId(supProjectId);
                int i = supplierProjectAcceptService.selectCount(accept);
                if (i > 0) {
                    re.setFlag(false);
                    re.setMsg("存在应接记录，无法撤销");
                }
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
                project.setStatus(supplierProjectDTO.getStatus());
                supplierProjectManagerService.updateByPrimaryKey(project);
                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }

    }

    /**
     * @param supplierProjectDTO
     * @Author:zhaoyongke
     * @Description:编辑基本信息
     * @Date:15:17 2021/3/24
     */
    @RequestMapping("/projectManager/updateSave")
    @ResponseBody
    public JsonUtil updateSave(SupplierProjectDTO supplierProjectDTO, HttpServletRequest request) {
        String flag = request.getParameter("flag");
        String yj = request.getParameter("yj");
        if (supplierProjectDTO != null || supplierProjectDTO.getSupProjectId() != null) {
            try {
                /*校验项目名称是重复*/
                Example e = new Example(SupplierProject.class);
                Example.Criteria c = e.createCriteria();
                c.andNotEqualTo("supProjectId", supplierProjectDTO.getSupProjectId());
                c.andEqualTo("projectName", supplierProjectDTO.getProjectName().trim());
                int count = supplierProjectManagerService.selectCountByExample(e);
                if (count > 0) {
                    return JsonUtil.error("修改项目失败:项目名称不允许重复");
                }
                SupplierProject supProject = supplierProjectManagerService.selectByPrimaryKey(supplierProjectDTO.getSupProjectId());
                if(!"001".equals(supProject.getStatus())){
                    // 验证提交供需项目未对招标时间是否晚于当前时间做校验
                    Date currdate = new Date();
                    Date zbEndDate = DateUtil.parseDate(supplierProjectDTO.getZbEndDate(), "yyyy-MM-dd HH:mm");
                    if(currdate.after(zbEndDate)){
                        return JsonUtil.error("招标截止时间应晚于当前时间！！");
                    }
                }
                //(1)保存基本信息
                String supProjectId = supProject.getSupProjectId();
                supplierProjectDTO.setProjectName(supplierProjectDTO.getProjectName().trim());
                String status = supProject.getStatus();
                String checkStatus = supProject.getCheckStatus();
                if ("1".equals(flag) && "1".equals(checkStatus)) {
                    return JsonUtil.error("提交失败：不能重复提交");
                }
                if ("0".equals(flag) && "1".equals(checkStatus)) {
                    return JsonUtil.error("保存失败：提交后不能操作保存");
                }
                if ("006".equals(status) && !"1".equals(yj)) {
                    if ("1".equals(flag)) {
                        supProject.setCheckStatus("1");//审核中
                        supProject.setCommitBy(CommonUtil.getUserId());
                        supProject.setCommitDate(DateUtil.getCurrentDateString());
                    } else if ("0".equals(flag)) {
                        supProject.setCheckStatus("0");//发布的项目编辑中
                    }
                    supplierProjectManagerService.updateByPrimaryKey(supProject);
                    if ("1".equals(checkStatus) && "0".equals(flag)) {
                        return JsonUtil.error("操作失败：审核中不能保存");
                    }
                    //已经发布 先保存到变更表中
                    SupplierProjectChangeDTO changeDTO = new SupplierProjectChangeDTO();
                    BeanUtil.copyNotNullBean(supplierProjectDTO, changeDTO);
                    changeDTO.setStatus("006");
                    saveProChange(changeDTO, supProject, flag);
                } else {
                    // 项目名称 001 已保存 002 待审核 003 已驳回 004 已结束 005 已撤销  006 已发布
                    // 001 保存 003驳回 005 撤销 状态下的项目编辑
                    //

                    saveUpdatePro(supplierProjectDTO, supProject, flag);

                }
                return JsonUtil.sucess("操作成功");

            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("修改项目失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }

    }

    /**
     * @param supplierProjectDTO
     * @param supProject
     * @param falg
     * @Author:zhaoyongke
     * @Description: 保存 驳回 撤销 状态的修改和提交
     * @Date:13:48 2021/3/29
     */
    public void saveUpdatePro(SupplierProjectDTO supplierProjectDTO, SupplierProject supProject, String falg) throws Exception {
        String status = supProject.getStatus();
        // 保存 驳回 撤销 状态的保存和提交
        BeanUtil.copyNotNullBean(supplierProjectDTO, supProject);
        if ("0".equals(falg)) {
            //保存
            supProject.setStatus(status);
        } else {
            //提交
          /*  if(!"001".equals(status) && !"003".equals(status) && !"005".equals(status)){
                return JsonUtil.error("修改项目失败:不允许重复提交");
            }*/
            supProject.setStatus("002");
            // 1 审核中 2 审核通过  3 审核不通过
            supProject.setCheckStatus("1");
            supProject.setCommitBy(CommonUtil.getUserId());
            supProject.setCommitDate(DateUtil.getCurrentDateString());
            // 发送消息
            saveSendNoticeAffirCase(supProject);
        }
        supplierProjectManagerService.updateByPrimaryKey(supProject);
        ProjectPlace placeDTO = new ProjectPlace();
        placeDTO.setSupProjectId(supProject.getSupProjectId());
        projectPlaceService.delete(placeDTO);
        //（2） 保存实施地点
        List<ProjectPlaceDTO> projectPlacedtos = supplierProjectDTO.getProjectPlacedtos();
        if(CollectionUtils.isEmpty(projectPlacedtos)){
             throw new  Exception("实施地点校验失败！！");
        }
        //（2） 保存实施地点
        supplierProjectManagerService.addPalce(supplierProjectDTO, supProject);
        //（3）保存人员地点
        supplierProjectManagerService.addPersonPalce(supplierProjectDTO, supProject);
        //保存文件
        List<String> tempFormFileIds = supplierProjectDTO.getTempFormFileIds();

        String  size="0";
        if(!CollectionUtils.isEmpty(tempFormFileIds)){
            size=tempFormFileIds.size()+"";

        }
        String text="2222222222saveUpdatePro方法保存之前tempFormFileIds"+size;
        supervisorFileTempService.insertTolalLog("ADDSuTemp",text,supProject.getSupProjectId());

        if (tempFormFileIds != null) {
            for (int i = 0; i < tempFormFileIds.size(); i++) {
                String tempId = tempFormFileIds.get(i);
                SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(tempId);
                supervisorFileTemp.setLinkId(supProject.getSupProjectId());
                supervisorFileTempService.updateByPrimaryKey(supervisorFileTemp);

                SysLog sysLog = new SysLog();
                sysLog.setCreateTime(new Date());
                sysLog.setType("ADDSuTemp");
                sysLog.setText("saveupdate方法2222=====");
                sysLog.setParam(tempFormFileIds.size()+"页面文件数量"+supervisorFileTemp.toString());
                sysLog.setIp(supProject.getSupProjectId());
                sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
                CurrentUser currentUser = Principal.getCurrentUse();
                sysLog.setUserName(currentUser.getUsername());
                sysLogMapper.insert(sysLog);
            }
        }
        String aftertext="2222222222saveUpdatePro方法保存之后tempFormFileIds"+size;
        supervisorFileTempService.insertTolalLog("ADDSuTemp",aftertext,supProject.getSupProjectId());


    }

    /**
     * @param changeDTO
     * @param supProject
     * @Author:zhaoyongke
     * @Description: 已发布的项目状态  保存和修改
     * @Date:13:50 2021/3/29
     */
    public void saveProChange(SupplierProjectChangeDTO changeDTO, SupplierProject supProject, String flag) throws Exception {
        /*已经发布的项目可以编辑*/
        //(1)---2 项目基本信息 先保存到项目临时表中
        SupplierProjectChange supplierProjectChange = new SupplierProjectChange();
        BeanUtil.copyNotNullBean(changeDTO, supplierProjectChange);
        supplierProjectChange.setStatus("006");
        if ("1".equals(flag)) {
            supplierProjectChange.setCheckStatus("1");
            supplierProjectChange.setCommitBy(CommonUtil.getUserId());
            supplierProjectChange.setCommitDate(DateUtil.getCurrentDateString());
        } else if ("0".equals(flag)) {
            //发布的项目编辑中
            supplierProjectChange.setCheckStatus("0");
        }
        supplierProjectChange.setPublishType(supProject.getPublishType());
        supplierProjectChange.setPubComType(supProject.getPubComType());
        supplierProjectChange.setPublishDate(supProject.getPublishDate());
        supplierProjectManagerChangeService.insertSelective(supplierProjectChange);
        changeDTO.setSupProjectChangeId(supplierProjectChange.getSupProjectChangeId());

        ProjectPlaceChange placeDTO = new ProjectPlaceChange();
        placeDTO.setSupProjectId(supProject.getSupProjectId());
        placeDTO.setSupProjectChangeId(supplierProjectChange.getSupProjectChangeId());
        projectPlaceChangeService.delete(placeDTO);

        List<ProjectPlaceDTO> projectPlacedtos = changeDTO.getProjectPlacedtos();
        if(CollectionUtils.isEmpty(projectPlacedtos)){
             throw  new  Exception("实施地点校验失败！！");
        }
        //（2） 保存实施地点
        supplierProjectManagerChangeService.addPalceChange(changeDTO, supProject);
        //（3）保存人员地点
        supplierProjectManagerChangeService.addPersonPalceChange(changeDTO, supProject);

        // 记录项目原有文件

        String text="88888888888888888saveUpdatePro方法保存之前tempFormFileIds"+changeDTO.getTempFormFileIds();
        supervisorFileTempService.insertTolalLog("ADDSuTemp",text,supplierProjectChange.getSupProjectId());

        // 原有项目的文件处理------
        SupervisorFileTemp temp = new SupervisorFileTemp();
        temp.setLinkId(supplierProjectChange.getSupProjectId());
        List<SupervisorFileTemp> selecttemp = supervisorFileTempService.select(temp);
        if (selecttemp != null) {
            for (int i = 0; i < selecttemp.size(); i++) {
                SupervisorFileTemp supervisorFileTemp = selecttemp.get(i);
                SupervisorFileTemp tempadd = new SupervisorFileTemp();
                BeanUtil.copyNotNullBean(supervisorFileTemp, tempadd);
                tempadd.setLinkId(supplierProjectChange.getSupProjectChangeId());
                tempadd.setId(IdUtil.simpleUUID());
                supervisorFileTempService.insertSelective(tempadd);
            }
        }

        //保存文件
        List<String> tempFormFileIds = changeDTO.getTempFormFileIds();
        if (tempFormFileIds != null) {
            for (int i = 0; i < tempFormFileIds.size(); i++) {
                String tempId = tempFormFileIds.get(i);
                SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(tempId);
                supervisorFileTemp.setLinkId(supplierProjectChange.getSupProjectChangeId());
                supervisorFileTempService.updateByPrimaryKey(supervisorFileTemp);
            }
        }

        SupervisorFileTemp supervisorFileTemp = new SupervisorFileTemp();
        supervisorFileTemp.setLinkId(supplierProjectChange.getSupProjectChangeId());
        List<SupervisorFileTemp> select = supervisorFileTempService.select(supervisorFileTemp);
        String  size="0";
        if(!CollectionUtils.isEmpty(select)){
            size=select.size()+"";
        }
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("ADDSuTemp");
        sysLog.setText("88888888888888888saveUpdatePro方法保存之后 supplierProjectChange 文件"+size);
        sysLog.setParam("文件数量===="+size+"文件详情"+select);
        sysLog.setIp(supplierProjectChange.getSupProjectId());
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        sysLog.setUserName(CommonUtil.getUser().getUsername());
        sysLogMapper.insert(sysLog);

        // 发送消息
        if ("1".equals(flag)) {
            saveSendNoticeAffirCase(supProject);
        }
        SupplierProjectDTO supdto = new SupplierProjectDTO();
        supdto.setSupProjectId(supProject.getSupProjectId());
        SupplierProjectChangeDTO changeProject = supplierProjectManagerChangeService.getChangeProject(supdto);
        affairService.addChangeRecord( supProject,  changeProject);

    }


    /**
     * @param supProject
     * @Author:zhaoyongke
     * @Description:审核人发送消息提醒
     * @Date:13:59 2021/3/27
     */
    public void saveSendNoticeAffirCase(SupplierProject supProject)  throws  Exception {
        SysUserDTO sysUserDTO = new SysUserDTO();
        // 发布审核人角色
        sysUserDTO.setUserRole("pucheckper");
        // 获取发布单位
        sysUserDTO.setCompanyName(supProject.getPublishCompany());
        // 获取发布人的部门 【市场一部 || 分支管理部】
        SysUserWorkExperience nowWork = new SysUserWorkExperience();
        nowWork.setSuId(supProject.getPublishBy());
        nowWork.setIfNow("1");
        SysUserWorkExperience  experience=null;
        List<SysUserWorkExperience> selectlist = userWorkExperienceService.select(nowWork);
        if(!CollectionUtils.isEmpty(selectlist)){
            experience=selectlist.get(0);
        }else{
            throw  new  Exception("请维护部门信息！");
        }

        sysUserDTO.setDeptName(experience.getDeptCode());
        List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);
        if(CollectionUtils.isEmpty(sysUsers)){
            throw  new  Exception("请维护发布审核人！");
        }
        List<String> userlist = new ArrayList<>();
        for (int i = 0; i < sysUsers.size(); i++) {
            userlist.add(sysUsers.get(i).getId());
        }
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("userList", userlist);
        //(1)启动流程
        String lcdyid = workflowService.startAffairWorkflowGx("您有一个新的供需项目（" + supProject.getProjectName() + "项目）需要审核", "PUCHECK", supProject.getSupProjectId(), "002", "000", variables);
    }




    /**
     * @param supplierProjectDTO
     * @Author:zhaoyongke
     * @Description:
     * @Date:10:16 2021/3/24
     */
    public SupplierProject addProject(SupplierProjectDTO supplierProjectDTO) throws Exception {
        supplierProjectDTO.setProjectName(supplierProjectDTO.getProjectName().trim());
        String userId = CommonUtil.getUserId();
        SysUser user = sysUserService.selectByPrimaryKey(userId);
        String source = user.getSource();
        SupplierProject supProject = new SupplierProject();
        BeanUtil.copyNotNullBean(supplierProjectDTO, supProject);
        String status = supplierProjectDTO.getStatus();
        if ("002".equals(status)) {
            //1 进行中 2 审核通过  3 审核不通过
            supProject.setCheckStatus("1");
            supProject.setCommitDate(DateUtil.getCurrentDateString());
            supProject.setCommitBy(CommonUtil.getUserId());
        }
        supProject.setStatus(supplierProjectDTO.getStatus());// 保存
        if ("001".equals(source)) {
            supProject.setPublishType("001");
            // 存公司Id
            supProject.setPubComType("001");
        } else {
            supProject.setPubComType("002");
            // 存人员Id
            supProject.setPublishType("002");
        }
        supProject.setSupProjectId(null);
        supplierProjectManagerService.insertSelective(supProject);
        return supProject;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:供方应接项目
     * @Date:13:17 2021/3/31
     */
    @RequestMapping("/projectManager/saveAcceptProject")
    @ResponseBody
    public JsonUtil saveAcceptProject(SupplierProjectAcceptDTO dto) {
        if (dto != null) {
            try {
                JsonUtil re = new JsonUtil();
                //--校验是否重复

                String supProjectId = dto.getSupProjectId();
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
             /*   if("1".equals(project.getZbStatus())){
                    return JsonUtil.error("操作失败:项目已经结束不能应接");
                }*/
                //到了截至日期就不可以应接
                Date currdate = new Date();
                Date zbEndDate = DateUtil.parseDate(project.getZbEndDate(), "yyyy-MM-dd HH:mm");
                if(currdate.after(zbEndDate)){
                    re.setMsg("招标截止日期已到不可以应接该项目");
                    re.setFlag(false);
                    return re;
                }

                SupplierProjectAccept accept = new SupplierProjectAccept();
                BeanUtil.copyNotNullBean(dto, accept);
                accept.setAcceptBy(CommonUtil.getUserId());
                accept.setAcceptDate(DateUtil.getCurrentDateString());
                // 获取总金额
                String acceptMoney = getAcceptMoney(accept, project);
                accept.setTotalMoney(acceptMoney);
                SysUser sysUser = getSysUser();
                //  供需类型 001 供方 002 需方
                String gxType = sysUser.getGxType();
                //001  002 组织
                String personType = sysUser.getPersonType();
                //  001 正中人员  002  项目生成 --审核之后变成003  003自行注册
                String source = sysUser.getSource();

                if ("002".equals(gxType)) {
                    return JsonUtil.error("操作失败:需方不能应接");
                }
                String companyId = "";
                if ("001".equals(personType)) {
                    if ("001".equals(source)) {
                        // 公司Id
                        accept.setCompanyId(sysUser.getCompanyName());
                        accept.setComType("001");
                    } else {
                        // 外部注冊的个人 默认 正中总部
                        accept.setCompanyId("1564895");
                        accept.setComType("001");
                    }

                } else {
                    // 组织

                    // 人员Id
                    accept.setCompanyId(CommonUtil.getUserId());
                    accept.setComType("002");
                }
                SupplierProjectAccept pro = new SupplierProjectAccept();
                pro.setAcceptBy(CommonUtil.getUserId());
                pro.setSupProjectId(dto.getSupProjectId());
                int countp = supplierProjectAcceptService.selectCount(pro);
                if (countp > 0) {
                    return JsonUtil.error("已经存在应接记录");
                }
                supplierProjectAcceptService.insertSelective(accept);
                // 保存投标文件
                List<String> tempFormFileIds = dto.getTempFormFileIds();
                List<SupervisorFileTemp> selectfilelist = new ArrayList<>();
                if (tempFormFileIds != null) {
                    for (int i = 0; i < tempFormFileIds.size(); i++) {
                        SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(tempFormFileIds.get(i));
                        supervisorFileTemp.setLinkId(accept.getSupAcceptId());
                        supervisorFileTempService.updateByPrimaryKey(supervisorFileTemp);
                        selectfilelist.add(supervisorFileTemp);
                    }
                }
                // 复制文件到 知识库目录 20210829 zyk
                String copyZskUrl = supervisorFileTempService.getCopyZskUrl(project);
                supervisorFileTempService.updateCopyFileToZsk( copyZskUrl,project,selectfilelist);
                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }

        } else {
            return JsonUtil.error("获取数据失败！！");
        }


    }

    /**
     * @param accept
     * @param project
     * @Author:zhaoyongke
     * @Description: 获取总费用
     * @Date:18:52 2021/4/12
     */
    public String getAcceptMoney(SupplierProjectAccept accept, SupplierProject project) {
        BigDecimal jemoney = new BigDecimal("0.00");
        // 计算总money
        String publishType = project.getPublishType();
        String projectType = project.getProjectType();
        if ("001".equals(publishType)) {
            //正中发布的项目 计算实施费用总额
            if (projectType.indexOf("001") > -1) {
                String jlSsMoney = accept.getJlSsMoney().trim();
                log.info(jlSsMoney+"监理实施费用");
                BigDecimal money = new BigDecimal(jlSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("002") > -1) {
                String zxSsMoney = accept.getZxSsMoney().trim();
                log.info(zxSsMoney+"咨询实施费用");
                BigDecimal money = new BigDecimal(zxSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("003") > -1) {
                String jcSsMoney = accept.getJcSsMoney().trim();
                BigDecimal money = new BigDecimal(jcSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("100") > -1) {
                String qtSsMoney = accept.getQtSsMoney().trim();
                BigDecimal money = new BigDecimal(qtSsMoney);
                jemoney = jemoney.add(money);
            }

        } else if ("002".equals(publishType)) {
            //计算服务费
            if (projectType.indexOf("001") > -1) {
                String jlFwMoney = accept.getJlFwMoney().trim();
                BigDecimal money = new BigDecimal(jlFwMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("002") > -1) {
                String zxFwMoney = accept.getZxFwMoney().trim();
                BigDecimal money = new BigDecimal(zxFwMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("003") > -1) {
                String jcFwMoney = accept.getJcFwMoney().trim();
                BigDecimal money = new BigDecimal(jcFwMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("100") > -1) {
                String qtFwMoney = accept.getQtFwMoney().trim();
                BigDecimal money = new BigDecimal(qtFwMoney);
                jemoney = jemoney.add(money);
            }

        }
        String jestr = jemoney.stripTrailingZeros().toPlainString();
        return jestr;
    }

    /**
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description: 查询应接记录
     * @Date:18:15 2021/3/31
     */
    @ApiOperation(value = "/projectManager/showAcceptProjectRecordList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/projectManager/showAcceptProjectRecordList")
    @ResponseBody
    public ReType showAcceptProjectRecordList(HttpServletRequest request, SupplierProjectDTO projectdto, Model model, String page, String limit) {
        String zbshr = request.getParameter("zbshr");
        String acceptOrder=request.getParameter("acceptOrder");
        String totalMoney=request.getParameter("totalMoney");

        SupplierProjectAcceptDTO acceptDTO = new SupplierProjectAcceptDTO();
        acceptDTO.setSupProjectId(projectdto.getSupProjectId());
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectdto);
        SysUser sysUser = getSysUser();
        //001 正中发布
        String publishType = project.getPublishType();
        String projectType = project.getProjectType();
        String gxType = sysUser.getGxType();
        if ("001".equals(gxType)) {
            //供方显示我的迎接
            acceptDTO.setAcceptBy(CommonUtil.getUserId());
        }
        if ("1".equals(zbshr)) {
            acceptDTO.setAcceptBy(null);

        }
        if(StringUtil.isBlank(acceptOrder)){
            totalMoney="333";
        }
        //最低价推荐
        acceptDTO.setTotalMoney(totalMoney);
        //综合推荐
        acceptDTO.setAcceptOrder(acceptOrder);
        ReType re = supplierProjectAcceptService.show(acceptDTO, Integer.valueOf(page), Integer.valueOf(limit));
        return re;

    }

    /*
     * 下载文件
     * */
    @GetMapping(value = "exportFile")
    public void exportFile(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");// 文件id
        String url = "";
        if (!StringUtil.isBlank(id)) {
            SupervisorFileTemp supervisorFile = new SupervisorFileTemp();
            supervisorFile.setId(id);
            supervisorFile = supervisorFileTempService.selectByPrimaryKey(supervisorFile);
            url = supervisorFile.getUrl();
        }
        ExportFileUtil.exportFile(response, request, url);
    }


    /**
     * 压缩后下载
     *
     * @param fileIds
     * @param request
     * @param response
     */
    @RequestMapping(value = "/dic/download")
    public void download(String fileIds, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(fileIds)) {
            List<String> splitids = StringUtil.split(fileIds);
            String dicName = "";
            String AsOutPath = tempPath + File.separator + dicName + DateUtil.getCurrentDateTimeStringNoSpliter() + ".zip";
            try {
                List<String> filePathList = new ArrayList<>();
                for (String fileid : splitids) {
                    SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(fileid);
                    if (StringUtils.isNotBlank(supervisorFileTemp.getUrl())) {
                        filePathList.add(supervisorFileTemp.getUrl());
                    }
                }
                ZipUtils.compress(AsOutPath, filePathList);

            } finally {
            }
            ExportFileUtil.exportFile(response, request, AsOutPath);

        }
    }

    /**
     * 压缩后下载
     *
     * @param projectId
     * @param request
     * @param response
     */
    @RequestMapping(value = "/dic/alldownload")
    public void Alldownload(String projectId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(projectId)) {
            String dicName = "";
            String AsOutPath = tempPath + File.separator + dicName + DateUtil.getCurrentDateTimeStringNoSpliter() + ".zip";
            try {
                List<String> filePathList = new ArrayList<>();
                SupervisorFileTemp tempfile = new SupervisorFileTemp();
                tempfile.setLinkId(projectId);
                List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(tempfile);
                for (SupervisorFileTemp file : selectfile) {
                    if (StringUtils.isNotBlank(file.getUrl())) {
                        filePathList.add(file.getUrl());
                    }
                }
                ZipUtils.compress(AsOutPath, filePathList);

            } finally {
            }
            ExportFileUtil.exportFile(response, request, AsOutPath);

        }
    }

    /**
     * @param ids
     * @Author:zhaoyongke
     * @Description: 删除临时文件
     * @Date:18:39 2021/4/5
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil deleteFile(String ids) {

        List<String> list = Tutil.split(ids);
        JsonUtil re = new JsonUtil();
        try {
            for (int i = 0; i < list.size(); i++) {
                String id = list.get(i);
                SupervisorFileTemp supervisorFileTemp = supervisorFileTempService.selectByPrimaryKey(id);
                String linkId = supervisorFileTemp.getLinkId();
                if(StringUtil.isNotBlank(linkId)){
                    SupervisorFile  file=new SupervisorFile();
                    file.setLinkId(linkId);
                    List<SupervisorFile> select = supervisorFileService.select(file);
                    if(select!=null){
                        for (int j = 0; j < select.size(); j++) {
                            SupervisorFile supervisorFile = select.get(i);
                            // 2 已经删除
                            supervisorFile.setDeleteState("2");
                            supervisorFileService.updateByPrimaryKey(supervisorFile);

                        }

                    }


                }
                supervisorFileTempService.deleteByPrimaryKey(id);
                // 删除正式文件




            }
            re.setMsg("删除成功");
            re.setFlag(true);
        } catch (
                Exception e) {
            re.setMsg("删除失败!" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 上传合同后的更新
     * @Date:10:21 2021/4/6
     */
    @RequestMapping("/projectManager/updateProHt")
    @ResponseBody
    public JsonUtil updateProHt(SupplierProjectDTO dto) {
        JsonUtil re = new JsonUtil();
        try {
            String supProjectId = dto.getSupProjectId();
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
            project.setIsSfk(dto.getIsSfk());
            project.setHtSignDate(dto.getHtSignDate());
            project.setQdHt("1");
            supplierProjectManagerService.updateByPrimaryKey(project);
            re.setMsg("操作成功");
            re.setFlag(true);
        } catch (
                Exception e) {
            re.setMsg("操作失败!" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;


    }

    /**
     * @Author:zhaoyongke
     * @Description:
     * @Date:10:47 2021/4/6
     */
    @GetMapping(value = "/projectManager/updateht")
    public String updateht(Model model, SupplierProjectDTO dto,String fileId) {
        String supProjectId = dto.getSupProjectId();
        model.addAttribute("supProjectId", supProjectId);
        model.addAttribute("fileId", fileId);
        return "projectManager/updateht";
    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description: 我的項目
     * @Date:14:34 2021/4/6
     */
    @GetMapping(value = "/projectManager/myproject")
    @RequiresPermissions("supplier:myproject")
    public String myproject(Model model) {

        SysUser sysUser = getSysUser();
        //001 供方 002 需方
        String gxType = sysUser.getGxType();
        if ("001".equals(gxType)) {
            model.addAttribute("gxtype", "g");
        } else if ("002".equals(gxType)) {
            model.addAttribute("gxtype", "x");
        }
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        model.addAttribute("projectTypeList", projectTypeList);
        return "projectManager/myproject";
    }


    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:项目列表  我的项目
     * @Date:18:16 2021/3/25
     */
    @ApiOperation(value = "/projectManager/myProjectList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/projectManager/myProjectList")
    @ResponseBody
    public ReType myProjectList(SupplierProjectDTO project, Model model, String page, String limit) {
        ReType re = new ReType();
        SysUser sysUser = getSysUser();
        //001 供方 002 需方
        String gxType = sysUser.getGxType();
        //需方展示自己发布的所有的项目，供方展示所有应接的项目。
        if ("002".equals(gxType)) {
            project.setCreateBy(CommonUtil.getUserId());
        } else if ("001".equals(gxType)) {
            //
            project.setAcceptBy(CommonUtil.getUserId());

        }

        Page<SupplierProjectDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupplierProjectDTO> list = supplierProjectManagerService.selectMyProjectList(project);
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(list);
        return re;


    }

    /**
     * 选择中标
     *
     * @param projectId
     * @param acceptId
     * @return
     */
    @RequestMapping("updatePitchOn")
    @ResponseBody
    public JsonUtil updatePitchOn(String projectId, String acceptId) {
        JsonUtil json = new JsonUtil();
        try {
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
            if (!"006".equals(project.getStatus())) {
                json.setFlag(false);
                json.setMsg("失败：只能操作已经发布状态的项目");
                return json;
            }
            // 2021 0902 外部项目发布人不应该可以在招标截至时间到期前就能直接选择中标人
            Date currdate = new Date();
            Date zbEndDate = DateUtil.parseDate(project.getZbEndDate(), "yyyy-MM-dd HH:mm");
            if(currdate.before(zbEndDate)){
                json.setFlag(false);
                json.setMsg("失败：招标截止时间到后才能选择中标人");
                return json;
            }
            updateZb(projectId, acceptId, "001");
            SupplierProjectAccept accept = supplierProjectAcceptService.selectByPrimaryKey(acceptId);
            //您发布的XXX项目中标人为XXX。
            sendNoticeToXfZb(projectId, accept.getAcceptBy(),project.getPublishType()+"自己选择中标人");
            json.setFlag(true);
            json.setMsg("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonUtil.error("操作失败:" + e.getMessage());
        }
        return json;
    }

    /**
     * @param projectId
     * @param acceptId
     * @Author:zhaoyongke
     * @Description:
     * @Date:16:45 2021/4/13
     */
    public void updateZb(String projectId, String acceptId, String type) throws Exception {
        String accpt1 = "";
        String time = DateUtil.getCurrentDateTimeString();
        //查询中标公司和未中标公司  更新状态
        SupplierProjectAccept notdto = new SupplierProjectAccept();
        notdto.setSupProjectId(projectId);
        List<SupplierProjectAccept> list = supplierProjectAcceptService.select(notdto);
        if (list != null && list.size() > 0) {
            for (SupplierProjectAccept a : list) {
                if ("001".equals(type)) {
                    if (!acceptId.equals(a.getSupAcceptId())) {
                        a.setIsZb("0");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                        //给未中标发消息
                        sendNoticeNotZb(a);
                    } else {
                        // 生成账号
                        saveCreateZh(a, projectId);
                        a.setZbDate(time);
                        a.setIsZb("1");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                        //给中标人发消息
                        sendNoticeZb(a);
                        // 给项目项目经理
                        // 中标后给相关项目经理发送信息通知
                        sendNoticeToXmjl(projectId, a, "需方同意推荐结果选择中标人");

                    }
                } else {
                    if (!acceptId.equals(a.getAcceptBy())) {
                        // 推荐的招标人
                        a.setIsZb("0");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                        //给未中标发消息
                        sendNoticeNotZb(a);
                    } else {
                        accpt1 = a.getSupAcceptId();
                        // 生成账号
                        saveCreateZh(a, projectId);
                        a.setZbDate(time);
                        a.setIsZb("1");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                        //给中标人发消息
                        sendNoticeZb(a);
                        sendNoticeToXmjl(projectId, a, "需方同意推荐结果选择中标人");
                    }

                }

            }
        }
        //更新中标项目
        String accId = acceptId;
        if ("001".equals(type)) {
            accId = acceptId;
        } else {
            accId = accpt1;
        }
        SupplierProjectAccept adto = supplierProjectAcceptService.selectByPrimaryKey(accId);
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        project.setZbStatus("1");
        project.setZbCompany(adto.getCompanyId());
        project.setZbDate(time);
        project.setZbComType(adto.getComType());
        project.setZbBy(adto.getAcceptBy());
        project.setSupProjectId(projectId);
        project.setStatus("004");
        supplierProjectManagerService.updateByPrimaryKey(project);
        // 中标后自动公示
        saveGs(project);
    }


    /**
     * @Author:zhaoyongke
     * @Description: 中标以后自动公示
     * @param dto
     * @Date:10:23 2021/9/8
     */
    public   void  saveGs(SupplierProject  dto){

        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(dto.getSupProjectId());
        SupplierProjectPubNotice  pubNotice=new SupplierProjectPubNotice();
        pubNotice.setSupProjectId(dto.getSupProjectId());
        pubNotice.setPubComType(project.getPubComType());
        pubNotice.setPubCompany(project.getPublishCompany());
        pubNotice.setStartDate(DateUtil.getCurrentDateString());
        String gsDays = dto.getGsDays();
        if(StringUtil.isNotBlank(gsDays)){
            Double aDouble = Double.valueOf(gsDays)*24;
            int  addHours = aDouble.intValue();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(Calendar.HOUR, addHours);
            Date dateend = new Date(calendar.getTimeInMillis());
            pubNotice.setEndDate(DateUtil.formatDate(dateend,"yyyy-MM-dd HH:mm"));
        }
        /**
         * 公示状态 0  未公示 1 公示中  2 结束
         */
        pubNotice.setGsStatus("1");
        // 中标人
        pubNotice.setZbBy(project.getZbBy());
        pubNotice.setSupProjectId(project.getSupProjectId());
        pubNotice.setZbComType(project.getZbComType());
        pubNotice.setZbCompany(project.getZbCompany());
        supplierProjectPubNoticeService.insertSelective(pubNotice);
        project.setIsGs("1");
        supplierProjectManagerService.updateByPrimaryKey(project);

    }


    //给中标人发消息
    public void sendNoticeZb(SupplierProjectAccept supa) {
        SupplierProject sup=supplierProjectManagerService.selectByPrimaryKey(supa.getSupProjectId());
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(supa.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(supa.getAcceptBy());
        if(sup!=null&&!"".equals(sup)){
            notice.setTitle("恭喜您中标" + sup.getProjectName() + "项目，请及时查看");
        }
        notice.setNoticeType("101");// 公示结束 发送消息
        notice.setApplicantType("002");// 供需
        notice.setCreateDate(DateUtil.getCurrentDateString());
        projectNoticeServie.insertSelective(notice);
    }
    //给未中标人发消息
    private void sendNoticeNotZb(SupplierProjectAccept supa){
        SupplierProject sup=supplierProjectManagerService.selectByPrimaryKey(supa.getSupProjectId());
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(supa.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(supa.getAcceptBy());
        if(sup!=null&&!"".equals(sup)){
            notice.setTitle("很遗憾您应接的" + sup.getProjectName() + "项目未中标，请及时查看");
        }
        notice.setNoticeType("101");// 公示结束 发送消息
        notice.setApplicantType("002");// 供需
        notice.setCreateDate(DateUtil.getCurrentDateString());
        projectNoticeServie.insertSelective(notice);
    }

    public void saveCreateZh(SupplierProjectAccept accept, String projectId) throws Exception {
        //  项目应接人----【供方合同负责人】角色权限
        String acceptBy = accept.getAcceptBy();
        SysUser sysUseraccept = sysUserService.selectByPrimaryKey(acceptBy);
        String personType = sysUseraccept.getPersonType();
        String source = sysUseraccept.getSource();
        //添加默认角色【供方合同负责人】角色权限
        List<String> initRoleList = new ArrayList<String>();
        initRoleList.add("gfhtperson");
        sysUserService.setMenuAndRolesWhenRegist(sysUseraccept, initRoleList);
        //输入的项目经理生成账号 和 权限
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        String projectType = project.getProjectType();
        if (projectType.indexOf("001") > -1) {
            //监理
            String jlManagerPerson = accept.getJlManagerPerson();
            if (StringUtil.isBlank(jlManagerPerson)) {
                String jlManagerPersonName = accept.getJlManagerPersonName();
                SysUser sysUser = saveCreateUser(jlManagerPersonName, sysUseraccept, "001", "xmjl");
                accept.setJlManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("002") > -1) {
            //咨询
            String zxManagerPerson = accept.getZxManagerPerson();
            if (StringUtil.isBlank(zxManagerPerson)) {
                String zxManagerPersonName = accept.getZxManagerPersonName();
                SysUser sysUser = saveCreateUser(zxManagerPersonName, sysUseraccept, "002", "zxxmjl");
                accept.setZxManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("003") > -1) {
            //检测
            String jcManagerPerson = accept.getJcManagerPerson();
            if (StringUtil.isBlank(jcManagerPerson)) {
                String jcManagerPersonName = accept.getJcManagerPersonName();
                SysUser sysUser = saveCreateUser(jcManagerPersonName, sysUseraccept, "003", "jcxmjl");
                accept.setJcManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("100") > -1) {
            //其他
            String qtManagerPerson = accept.getQtMagagerPerson();
            if (StringUtil.isBlank(qtManagerPerson)) {
                String qtManagerPersonName = accept.getQtManagerPersonName();
                SysUser sysUser = saveCreateUser(qtManagerPersonName, sysUseraccept, "100", "qtxmjl");
                accept.setQtMagagerPerson(sysUser.getId());
            }

        }


    }

    /**
     * @param realName
     * @param sysUseraccept
     * @param ywType
     * @param roleName
     * @Author:zhaoyongke
     * @Description: 创建账号
     * @Date:11:30 2021/4/9
     */
    public SysUser saveCreateUser(String realName, SysUser sysUseraccept, String ywType, String roleName) throws Exception {
        SysUser user = new SysUser();
        user.setUsername(realName);
        if ("001".equals(sysUseraccept.getPersonType())) {
            // 个人
        } else {
            // 组织
            user.setCompanyName(sysUseraccept.getCompanyName());
        }
        user.setSource("002");
        // 供需类型
        user.setGxType("001");
        // 人員类型
        user.setPersonType(sysUseraccept.getPersonType());
        user.setYwType(ywType);
        saveNewUserIdForProjectLeaderAndUnits(user);
        // 赋予角色
        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add(roleName);
        sysUserService.setMenuAndRolesWhenRegist(user, userRoleNameList);
        return user;
    }

    /**
     * 注册新用户,
     * 查找系统中是否存在同名用户
     * 如果存在同名用户,
     * 如果同一个公司中存在同名用户,给user设置id为该同名用户id
     * 如果同名用户不为同一个公司,那么根据规则生成新用户,给user设置新生成的用户id
     *
     * @param user
     * @return
     */
    public void saveNewUserIdForProjectLeaderAndUnits(SysUser user) throws Exception {
        SysUser sameNameUser = new SysUser();
        sameNameUser.setRealName(user.getUsername());
        //查询同名的用户
        List<SysUser> listuser = sysUserService.select(sameNameUser);
        Integer count = 0;
        if (listuser.size() > 0) {
            //存在相同username的账号
       /*     SysUser realNameUser = new SysUser();
            realNameUser.setRealName(user.getUsername());
            List<SysUser> listuserReal = sysUserService.select(realNameUser);*/
            for (int i = 0; i < listuser.size(); i++) {
                //相同公司 相同姓名
                SysUser dbUser = listuser.get(i);
                String dbCompanyName = dbUser.getCompanyName() + "";
                String dbRealName = dbUser.getRealName() + "";
                if (dbRealName.equals(user.getUsername()) && (user.getCompanyName() + "").equals(dbCompanyName)) {
                    // 相同姓名 相同公司
                    user.setId(dbUser.getId());
                    return;
                } else if (dbRealName.equals(user.getUsername()) && !dbCompanyName.equals(user.getCompanyName())) {
                    // 相同姓名不同公司
                    count++;
                } else {
                    //不同姓名 公司相同、不同姓名不同公司
                    count++;
                }
            }
        }
        //生成账号
        SysUser newUser = new SysUser();
        //获取用户名
        String username = getUserName(user, count);
        newUser.setUsername(username);
        newUser.setCompanyName(user.getCompanyName());
        newUser.setPassword("12345678");
        newUser.setRealName(user.getUsername());
        newUser.setGxType(user.getGxType());
        newUser.setYwType(user.getYwType());
        newUser.setPersonType(user.getPersonType());
        newUser.setSource(user.getSource());
        newUser.setCreateDate(DateUtil.getCurrentDateTime());
        sysUserService.setUserFilePath(newUser);
        sysUserService.insertSelective(newUser);

        SysUserWorkExperience nowWork = user.getNowWork();
        if (nowWork != null) {
            sysUserService.setUserFilePath(newUser);
            nowWork.setIfNow("1");
            nowWork.setSuId(newUser.getId());
            userWorkExperienceService.insertSelective(nowWork);
        }

        user.setId(newUser.getId());
        user.setUsername(newUser.getUsername());
        user.setRealName(newUser.getRealName());

    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description: 获取用户名
     * @Date:17:51 2020/12/31
     */
    public String getUserName(SysUser user, int count) {
        String userName = setUserName(user, count);
        int countUser = sysUserService.checkUser(userName);
        if (countUser != 0) {
            count = count + 1;
            userName = setUserName(user, count);
            int countUser1 = sysUserService.checkUser(userName);
            if (countUser1 > 0) {
                userName = getUserName(user, count);
            }
        }
        return userName;
    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description:设置用户名
     * @Date:17:51 2020/12/31
     */
    public String setUserName(SysUser user, int count) {
        SysUser newUser = new SysUser();
        if (count > 0) {
            newUser.setUsername(user.getUsername() + "0" + count);
        } else {
            newUser.setUsername(user.getUsername());
        }
        return newUser.getUsername();
    }

    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:导航到变更公告页面
     * @Date:14:46 2021/4/9
     */
    @GetMapping(value = "/projectManager/changeIndex")
    @RequiresPermissions("supplier:changeGg")
    public String changeIndex(Model model) {
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        model.addAttribute("projectTypeList", projectTypeList);
        return "projectManager/changeIndex";
    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:变更公告列表
     * @Date:15:09 2021/4/9
     */
    @ApiOperation(value = "/projectManager/showChangeList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/projectManager/showChangeList")
    @ResponseBody
    public ReType showChangeList(SupplierProjectDTO project, Model model, String page, String limit) {
        Subject subject = SecurityUtils.getSubject();
        // 2022/03/24
        if ( subject.hasRole("scry") || subject.hasRole("gxjl") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")){
            // 获取当前登录人的用户信息
            SysUser user = sysUserService.selectByPrimaryKey(CommonUtil.getUserId());
            // 根据公司查询
            project.setCompanyName(user.getCompanyName());
            // 根据部门查询
            // 获取发布人的部门 【市场一部 || 分支管理部】
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setSuId(user.getId());
            nowWork.setIfNow("1");
            SysUserWorkExperience experience =null;
            List<SysUserWorkExperience> selectlist = userWorkExperienceService.select(nowWork);
            if(!CollectionUtils.isEmpty(selectlist)){
                experience=selectlist.get(0);
                project.setDeptName(experience.getDeptCode());
            }else{
                project.setDeptName("1111");
            }

        }



        ReType re = new ReType();
        Page<SupplierProjectDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        SupplierProjectChange change = new SupplierProjectChange();
        change.setCheckStatus("2");
        List<SupplierProjectDTO> list = supplierProjectManagerService.selectProjectChangeList(project);
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(list);
        return re;

    }


    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:13:02 2021/4/8
     */
    @GetMapping(value = "/projectManager/changeDetail")
    public String changeDetail(Model model, SupplierProjectChangeDTO dto,String caseId) {
        SysUser sysUser = getSysUser();
        String supProjectChangeId = dto.getSupProjectChangeId();
        SupplierProjectChange supplierProjectChange = supplierProjectManagerChangeService.selectByPrimaryKey(supProjectChangeId);
        String supProjectId = supplierProjectChange.getSupProjectId();
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        if (StringUtil.isNotBlank(supplierProjectChange.getProjectType())) {
            //項目類型
            String proTypestr = getLxText(supplierProjectChange.getProjectType(), DictTypes.YW_TYPE.getType());
            model.addAttribute("strprojecttype", proTypestr);
        }
        if (StringUtil.isNotBlank(caseId)) {
            //修改提醒状态
            ProjectNotice projectNotice = projectNoticeServie.selectByPrimaryKey(caseId);
            projectNotice.setIsView("1");
            projectNoticeServie.updateByPrimaryKey(projectNotice);
        }
        String createBy = project.getCreateBy();
        String companyName = getFbdwByUser(createBy);
        SysUser sysUser1 = sysUserService.selectByPrimaryKey(createBy);
        model.addAttribute("user", sysUser1);
        model.addAttribute("project", project);
        model.addAttribute("companyName", companyName);
        model.addAttribute("supProjectChangeId", supProjectChangeId);
        model.addAttribute("change", supplierProjectChange);
        return "projectManager/changeDetail";
    }

    @GetMapping(value = "/projectManager/viewChangeDetail")
    public String viewChangeDetail(Model model, SupplierProjectDTO dto) {
        SupplierProjectChange change = new SupplierProjectChange();
        change.setSupProjectId(dto.getSupProjectId());
        change.setCheckStatus("2");
        List<SupplierProjectChange> select = supplierProjectManagerChangeService.select(change);
        if (select.size() > 0) {
            if (select.size() > 1) {
                model.addAttribute("list", select);
                return "projectManager/changeListDetail";
            } else {
                SupplierProjectChange supplierProjectChange = select.get(0);
                String supProjectId = supplierProjectChange.getSupProjectId();
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
                if (StringUtil.isNotBlank(supplierProjectChange.getProjectType())) {
                    //項目類型
                    String proTypestr = getLxText(supplierProjectChange.getProjectType(), DictTypes.YW_TYPE.getType());
                    model.addAttribute("strprojecttype", proTypestr);
                }
                String createBy = project.getCreateBy();
                String companyName = getFbdwByUser(createBy);
                SysUser sysUser1 = sysUserService.selectByPrimaryKey(createBy);
                model.addAttribute("user", sysUser1);
                model.addAttribute("project", project);
                model.addAttribute("companyName", companyName);
                model.addAttribute("change", supplierProjectChange);
                model.addAttribute("supProjectChangeId", supplierProjectChange.getSupProjectChangeId());

                return "projectManager/changeDetail";
            }

        } else {

        }


        return "projectManager/changeDetail";
    }

    /**
     * @param model
     * @param dto
     * @Author:zhaoyongke
     * @Description:查询是否有变更记录
     * @Date:18:50 2021/4/8
     */
    @GetMapping(value = "/projectManager/queryChangeCount")
    @ResponseBody
    public JsonUtil queryChangeCount(Model model, SupplierProjectDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        SupplierProjectChange change = new SupplierProjectChange();
        change.setSupProjectId(dto.getSupProjectId());
        change.setCheckStatus("2");
        List<SupplierProjectChange> select = supplierProjectManagerChangeService.select(change);
        if (select.size() == 0) {
            jsonUtil.setMsg("没有变更记录");
            jsonUtil.setFlag(false);
        } else {
            jsonUtil.setMsg("成功");
            jsonUtil.setFlag(true);
        }

        return jsonUtil;
    }


    /**
     * @param userId
     * @Author:zhaoyongke
     * @Description: 获取发布单位
     * @Date:10:24 2021/4/7
     */
    public String getFbdwByUser(String userId) {
        String companyName = "";
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        String source = sysUser.getSource();
        if ("001".equals(source)) {
            // 正中人员
            String companyId = sysUser.getCompanyName();
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName = baseCompany.getBcName();
        } else {
            companyName = sysUser.getCompanyName();
        }
        return companyName;

    }

    /**
     * @Author:zhaoyongke
     * @Description: 获取应接单位
     * @Date:10:24 2021/4/7
     */
    public String getAcceptdwByUser(SupplierProjectAccept accept) {
        String acceptBy = accept.getAcceptBy();
        SysUser sysUser = sysUserService.selectByPrimaryKey(acceptBy);
        String comType = accept.getComType();
        String companyName = "";
        if ("001".equals(comType)) {
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(accept.getCompanyId());
            companyName = baseCompany.getBcName();

        } else {
            companyName = sysUser.getCompanyName();
        }
        return companyName;

    }

    /**
     * @param dto
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:11 2021/4/10
     */
    @GetMapping(value = "viewUserDetail")
    public String viewUserDetail(SupplierProjectDTO dto, Model model) {
        String supProjectId = dto.getSupProjectId();
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        String zbBy = project.getZbBy();
        SupplierProjectAccept accept = new SupplierProjectAccept();
        accept.setAcceptBy(zbBy);
        accept.setSupProjectId(supProjectId);
        List<SupplierProjectAccept> select = supplierProjectAcceptService.select(accept);
        SupplierProjectAccept accept1 = select.get(0);
        SysUser userAccept = sysUserService.selectByPrimaryKey(accept1.getAcceptBy());
        String personType = userAccept.getPersonType();
        // 如果应接人是组织 查询联系人
        if("002".equals(personType)){
            userAccept.setRealName(userAccept.getLinkPerson());
        }
        model.addAttribute("userAccept", userAccept);
        String acceptComName = getAcceptdwByUser(accept1);
        String projectType = project.getProjectType();
        if (projectType.indexOf("001") > -1) {
            //监理
            String jlManagerPerson = accept1.getJlManagerPerson();
            SysUser sysUser = sysUserService.selectByPrimaryKey(jlManagerPerson);
            String realName = sysUser.getRealName();
            String personType1 = sysUser.getPersonType();
            if("002".equals(personType1)){
                if(StringUtil.isBlank(realName)){
                    sysUser.setRealName(sysUser.getLinkPerson());
                }
            }
            model.addAttribute("jlxmjl", sysUser);
        }
        if (projectType.indexOf("002") > -1) {
            //咨询
            String zxManagerPerson = accept1.getZxManagerPerson();
            SysUser sysUser = sysUserService.selectByPrimaryKey(zxManagerPerson);
            String realName = sysUser.getRealName();
            String personType1 = sysUser.getPersonType();
            if("002".equals(personType1)){
                if(StringUtil.isBlank(realName)){
                    sysUser.setRealName(sysUser.getLinkPerson());
                }
            }
            model.addAttribute("zxxmjl", sysUser);

        }
        if (projectType.indexOf("003") > -1) {
            //检测
            String jcManagerPerson = accept1.getJcManagerPerson();
            SysUser sysUser = sysUserService.selectByPrimaryKey(jcManagerPerson);
            String realName = sysUser.getRealName();
            String personType1 = sysUser.getPersonType();
            if("002".equals(personType1)){
                if(StringUtil.isBlank(realName)){
                    sysUser.setRealName(sysUser.getLinkPerson());
                }
            }
            model.addAttribute("jcxmjl", sysUser);
        }
        if (projectType.indexOf("100") > -1) {
            //其他
            String qtManagerPerson = accept1.getQtMagagerPerson();
            SysUser sysUser = sysUserService.selectByPrimaryKey(qtManagerPerson);
            String realName = sysUser.getRealName();
            String personType1 = sysUser.getPersonType();
            if("002".equals(personType1)){
                if(StringUtil.isBlank(realName)){
                    sysUser.setRealName(sysUser.getLinkPerson());
                }
            }
            model.addAttribute("qtxmjl", sysUser);
        }
        model.addAttribute("acceptComName", acceptComName);
        model.addAttribute("project", project);
        return "projectManager/zhNoticeDetail";
    }

    /**
     * @param dto
     * @param acceptDTO
     * @param model
     * @Author:zhaoyongke
     * @Description: 议价填写最低实施费用
     * @Date:19:19 2021/4/12
     */
    @GetMapping(value = "yjDetail")
    public String yjDetail(SupplierProjectDTO dto, SupplierProjectAcceptDTO acceptDTO, Model model) {
        String supProjectId = dto.getSupProjectId();
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        String supAcceptId = acceptDTO.getSupAcceptId();
        model.addAttribute("supAcceptId", supAcceptId);
        model.addAttribute("project", project);
        return "projectManager/yjDetail";
    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:供方应接项目
     * @Date:13:17 2021/3/31
     */
    @RequestMapping("/projectManager/saveUpdateAcceptProjectFy")
    @ResponseBody
    public JsonUtil saveUpdateAcceptProjectFy(SupplierProjectAcceptDTO dto) {
        if (dto != null) {
            try {
                JsonUtil re = new JsonUtil();
                String supAcceptId = dto.getSupAcceptId();
                SupplierProjectAccept accept = supplierProjectAcceptService.selectByPrimaryKey(supAcceptId);
                String supProjectId = accept.getSupProjectId();
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
                String tjStatus = project.getTjStatus();
                if ("1".equals(tjStatus)) {
                    re.setFlag(false);
                    re.setMsg("失败：已经推荐过中标人，不允许修改费用");
                    return re;
                }
                if (!"006".equals(project.getStatus())) {
                    re.setFlag(false);
                    re.setMsg("失败：只能操作已发布状态的项目");
                    return re;
                }
                if ("1".equals(project.getYjStatus())) {
                    if (project.getYjNum() != null) {
                        if (project.getYjNum() > 3) {
                            re.setFlag(false);
                            re.setMsg("失败：最多比较3次，不允许填写实施费用");
                            return re;
                        }
                    }
                    BeanUtil.copyNotNullBean(dto, accept);
                    supplierProjectAcceptService.updateByPrimaryKey(accept);
                    //所有的最低价迎接人填写完毕后，再次比价
                    String yjPerson = project.getYjPerson();
                    if (StringUtil.isNotBlank(yjPerson)) {
                        String newperson = updateYjPeron(yjPerson);
                        project.setYjPerson(newperson);
                        supplierProjectManagerService.updateByPrimaryKey(project);
                        if (StringUtil.isBlank(newperson)) {
                            updateYjBj(project);
                        }
                    }
                }else{
                    BeanUtil.copyNotNullBean(dto, accept);
                    supplierProjectAcceptService.updateByPrimaryKey(accept);
                }


                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }

        } else {
            return JsonUtil.error("获取数据失败！！");
        }
    }

    /**
     * @param yjPerson
     * @Author:zhaoyongke
     * @Description: 更新提交的实施费用 应接人 ，如果应接人为空，则说明都已提交  ，都提交后自动比价
     * @Date:20:22 2021/4/14
     */
    public String updateYjPeron(String yjPerson) {
        String newPerson = "";
        String userId = CommonUtil.getUserId();
        if (StringUtil.isNotBlank(yjPerson)) {
            int j = -1;
            List<String> list = Tutil.split(yjPerson);
            List<String> arrayList = new ArrayList(list);
            for (int i = 0; i < arrayList.size(); i++) {
                String s = arrayList.get(i);
                System.out.println(s + "测试");
                if (s.indexOf(userId) > -1) {
                    j = i;
                    break;
                }

            }
            if (j != -1) {
                arrayList.remove(j);
            }
            if (arrayList.size() == 0) {
                return "";
            } else {
                newPerson = arrayList.toString().replaceAll("\\[", "").replaceAll("\\]", "");
            }
        }
        return newPerson;
    }

    /**
     * @param project
     * @Author:zhaoyongkeupdateYjBj
     * @Description: 议价环节---- 价格最低的应接人，填写实施费后，比价
     * @Date:15:07 2021/4/14
     */
    public void updateYjBj(SupplierProject project) {
        Boolean isyj = false;
        // 到了 招标截止时间
        SupplierProjectAcceptDTO acceptDTO = new SupplierProjectAcceptDTO();
        acceptDTO.setSupProjectId(project.getSupProjectId());
        acceptDTO.setScoreDesc("desc");
        List<SupplierProjectAcceptDTO> acceptlist = supplierProjectAcceptService.selectListByScore(acceptDTO);
        if (acceptlist.size() == 1) {
            // 有一人应接的情况   推荐中标
            ProjectNotice notice = new ProjectNotice();
            notice.setLinkId(project.getSupProjectId());
            notice.setNoticeType("107");
            notice.setTjPerson(acceptlist.get(0).getAcceptBy());
            int y1 = projectNoticeServie.selectCount(notice);
            if (y1 == 0) {
                sendNoticeToXfTjzb(project, acceptlist.get(0));
            }
            project.setTjStatus("1");// 结束
            project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
            supplierProjectManagerService.updateByPrimaryKey(project);
        } else if (acceptlist.size() > 1) {
            //有最低价选择最低价  推荐中标
            SupplierProjectAcceptDTO dto = new SupplierProjectAcceptDTO();
            dto.setSupProjectId(project.getSupProjectId());
            List<SupplierProjectAcceptDTO> supplierProjectAcceptDTOS = supplierProjectAcceptService.selectAcceptByScore(dto);
            SupplierProjectAcceptDTO acceptDTO1 = supplierProjectAcceptDTOS.get(0);
            String num = acceptDTO1.getNum();
            if ("1".equals(num)) {
                //推荐最低价
                String totalMoney = acceptDTO1.getTotalMoney();
                SupplierProjectAccept accpet = new SupplierProjectAccept();
                accpet.setSupProjectId(project.getSupProjectId());
                accpet.setTotalMoney(totalMoney);
                List<SupplierProjectAccept> select = supplierProjectAcceptService.select(accpet);
                if (select.size() > 0) {
                    ProjectNotice notice = new ProjectNotice();
                    notice.setLinkId(project.getSupProjectId());
                    notice.setNoticeType("107");
                    notice.setTjPerson(acceptDTO1.getAcceptBy());
                    int y1 = projectNoticeServie.selectCount(notice);
                    if (y1 == 0) {
                        SupplierProjectAccept accept = select.get(0);
                        sendNoticeToXfTjzb(project, accept);
                    }
                }
                project.setTjStatus("1");// 结束
                project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                supplierProjectManagerService.updateByPrimaryKey(project);
            } else {
                //如果有多家相同的最低价，则给最低价的应接人发送议价通知
                Integer yjnum = project.getYjNum();
                if (yjnum < 1) {
                    String totalMoney = acceptDTO1.getTotalMoney();
                    SupplierProjectAcceptDTO fjydto = new SupplierProjectAcceptDTO();
                    fjydto.setTotalMoney(totalMoney);
                    fjydto.setSupProjectId(project.getSupProjectId());
                    List<SupplierProjectAccept> select = supplierProjectAcceptService.select(fjydto);
                    ArrayList<String> jypersonlist = new ArrayList<>();
                    for (int j = 0; j < select.size(); j++) {
                        SupplierProjectAccept accept = select.get(j);
                        // 发送议价通知
                        supplierProjectManagerService.sendNoticeToYj(project, accept,"供方提交生成议价");
                        isyj = true;
                        jypersonlist.add(accept.getAcceptBy());
                    }
                    if (isyj) {
                        String jypersonliststr = jypersonlist.toString();
                        String yjperson = "";
                        if (StringUtil.isNotBlank(jypersonliststr)) {
                            //截取前后【】
                            yjperson = jypersonliststr.replaceAll("\\[", "").replaceAll("\\]", "");
                        }
                        project.setYjPerson(yjperson);
                    }
                } else {
                    //如果还是有相同的则系统自动推荐应接人中综合评分排行第一的为中标人
                    SupplierProjectAcceptDTO scoredto = new SupplierProjectAcceptDTO();
                    scoredto.setSupProjectId(project.getSupProjectId());
                    scoredto.setAcceptOrder("333");
                    List<SupplierProjectAcceptDTO> supplierProjectAcceptDTOS1 = supplierProjectAcceptService.selectListByScore(scoredto);
                    if (supplierProjectAcceptDTOS1.size() > 0) {
                        SupplierProjectAcceptDTO acceptDTO2 = supplierProjectAcceptDTOS1.get(0);
                        ProjectNotice notice = new ProjectNotice();
                        notice.setLinkId(project.getSupProjectId());
                        notice.setNoticeType("107");
                        int y1 = projectNoticeServie.selectCount(notice);
                        if (y1 == 0) {
                            sendNoticeToXfTjzb(project, acceptDTO2);
                        }
                        project.setTjStatus("1");// 结束
                        project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                        supplierProjectManagerService.updateByPrimaryKey(project);
                    }

                }

            }

        }
        if (isyj) {
            project.setYjNum(project.getYjNum() + 1);
            project.setYjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
            supplierProjectManagerService.updateByPrimaryKey(project);
        }

    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 中标审核人推荐中标
     * @Date:16:56 2021/4/13
     */
    @RequestMapping("/projectManager/saveUpdateTjZb")
    @ResponseBody
    public JsonUtil saveUpdateTjZb(SupplierProjectDTO dto) {
        if (dto != null) {
            try {
                JsonUtil re = new JsonUtil();
                String proId = dto.getSupProjectId();
                String checkstatus = dto.getCheckStatus();
                String tjPerson = dto.getTjperson();
                if (StringUtil.isBlank(proId) || StringUtil.isBlank(checkstatus) || StringUtil.isBlank(tjPerson)) {
                    re.setFlag(false);
                    re.setMsg("获取参数失败");
                    return re;
                }
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(proId);
                if (!"006".equals(project.getStatus())) {
                    re.setFlag(false);
                    re.setMsg("只能操作已发布状态的项目");
                    return re;
                }

                AffairRecord recordquery = new AffairRecord();
                recordquery.setYwType("000");
                recordquery.setOperUserId(CommonUtil.getUserId());
                recordquery.setYwId(dto.getSupProjectId());
                List<AffairRecord> select = affairRecordService.select(recordquery);
                if (select.size() > 0) {
                    // 更新操作
                    AffairRecord record = select.get(0);
                    record.setCheckStatus(dto.getCheckStatus());
                    affairRecordService.updateByPrimaryKey(record);
                } else {
                    AffairRecord record = new AffairRecord();
                    record.setCheckStatus(dto.getCheckStatus());
                    //
                    record.setYwId(dto.getSupProjectId());
                    // 存入推荐人
                    record.setTaskId(dto.getTjperson());
                    record.setYwId(dto.getSupProjectId());
                    record.setOperUserId(CommonUtil.getUserId());
                    record.setOperDate(DateUtil.getCurrentDateString());
                    record.setYwType("000");
                    record.setRemark(dto.getRemark());
                    affairRecordService.insert(record);
                }
                // 判断所有的中标审核人是否都审核过
                AffairRecord recordquerycheck = new AffairRecord();
                recordquerycheck.setYwType("000");
                recordquerycheck.setYwId(dto.getSupProjectId());
                recordquerycheck.setCheckStatus("2");
                List<AffairRecord> selectcheck = affairRecordService.select(recordquerycheck);

                // 中标审核人角色
                SysUserDTO sysUserDTO = new SysUserDTO();
                sysUserDTO.setUserRole("zbCheckPerson");
                // 获取发布单位
                sysUserDTO.setCompanyName(project.getPublishCompany());
                // 获取项目类型
                String projectType = project.getProjectType();
                ArrayList<String>  listdept=new ArrayList<>();
                if(projectType.indexOf("001")>-1){
                    // 监理类型 对应工程部
                    listdept.add("001");
                }
                if(projectType.indexOf("002")>-1){
                    listdept.add("003");
                }
                if(projectType.indexOf("003")>-1){
                    listdept.add("004");
                }
                String deptNames = StringUtils.join(listdept, ",");
                sysUserDTO.setDeptNames(deptNames);
                List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);

                if (sysUsers.size() == selectcheck.size()) {
                    // 都审核完毕
                    AffairRecord record = selectcheck.get(0);
                    //意见一致 审核通过 更新中标结果
                    String ywId = record.getYwId();
                    String tjzbperson = record.getTaskId();
                    //根据推荐人 更新中标结果
                    updateZb(ywId, tjzbperson, "002");
                    //项目中标人确定后推送消息给发布人：您发布的XXX项目中标人为XXX。
                    // 给需方发送消息
                    //您发布的XXX项目中标人为XXX。
                    sendNoticeToXfZb(ywId, tjzbperson,"内部发布的项目--推荐中标后中标审核人都同意推荐结果");

                    re.setData("1");

                }
                SupplierProject projectnew = supplierProjectManagerService.selectByPrimaryKey(proId);
                projectnew.setIsConfirm(checkstatus);
                supplierProjectManagerService.updateByPrimaryKey(projectnew);
                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }

        } else {
            return JsonUtil.error("获取数据失败！！");
        }


    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:41 2021/4/15
     */
    @RequestMapping("/projectManager/saveWbUpdateTjZb")
    @ResponseBody
    public JsonUtil saveWbUpdateTjZb(SupplierProjectDTO dto) {


        if (dto != null) {
            try {
                JsonUtil re = new JsonUtil();
                String proId = dto.getSupProjectId();
                String checkstatus = dto.getCheckStatus();
                String tjPerson = dto.getTjperson();
                if (StringUtil.isBlank(proId) || StringUtil.isBlank(checkstatus) || StringUtil.isBlank(tjPerson)) {
                    re.setFlag(false);
                    re.setMsg("获取参数失败");
                    return re;
                }
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(proId);
                if (!"006".equals(project.getStatus())) {
                    re.setFlag(false);
                    re.setMsg("只能操作已发布状态的项目");
                    return re;
                }
                if ("2".equals(checkstatus)) {
                    //根据推荐人 更新中标结果
                    updateZb(proId, tjPerson, "002");
                    //项目中标人确定后推送消息给发布人：您发布的XXX项目中标人为XXX。
                    // 给需方发送消息
                    //您发布的XXX项目中标人为XXX。
                    sendNoticeToXfZb(proId, tjPerson,"外部发布的项目--需方同意推荐结果选择中标人");

                    // 更新推荐 中标 消息  为 已经处理完成
                    // updateNoticeTj(proId,"105");
                    re.setData("1");
                }
                SupplierProject projectnew = supplierProjectManagerService.selectByPrimaryKey(proId);
                projectnew.setIsConfirm(checkstatus);
                if("3".equals(checkstatus)){
                    projectnew.setRemark(dto.getRemark());
                }
                supplierProjectManagerService.updateByPrimaryKey(projectnew);
                re.setFlag(true);
                re.setMsg("操作成功");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }

        } else {
            return JsonUtil.error("获取数据失败！！");
        }


    }


//    public   void updateNoticeTj(String proId,String type){
//        ProjectNotice  notice=new ProjectNotice();
//        notice.setLinkId(proId);
//        notice.setSendTo(CommonUtil.getUserId());
//        notice.setNoticeType(type);
//        List<ProjectNotice> select = projectNoticeServie.select(notice);
//        if(select!=null){
//            if(select.size()>0){
//                for (int i = 0; i <select.size() ; i++) {
//                    ProjectNotice notice1 = select.get(i);
//                    notice1.setStatus("1");
//                    projectNoticeServie.updateByPrimaryKey(notice1);
//                }
//            }
//        }
//    }
    /**
     * @param request
     * @param dto
     * @Author:zhaoyongke
     * @Description: 查询审核意见（中标审核人）
     * @Date:10:25 2021/4/14
     */
    @RequestMapping("/projectManager/queryCheckRemark")
    @ResponseBody
    public JsonUtil queryCheckRemark(HttpServletRequest request, SupplierProjectDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        String projectId = dto.getSupProjectId();
        if (StringUtil.isNotBlank(projectId)) {
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
            if (!"006".equals(project.getStatus())) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("失败：只能操作已发布状态的项目");
                return jsonUtil;
            }
            AffairRecord recordquery = new AffairRecord();
            recordquery.setYwType("000");
            recordquery.setOperUserId(CommonUtil.getUserId());
            recordquery.setYwId(projectId);
            List<AffairRecord> select = affairRecordService.select(recordquery);
            if (select.size() > 0) {
                AffairRecord recordquerycount = new AffairRecord();
                recordquerycount.setYwType("000");
                recordquerycount.setYwId(dto.getSupProjectId());
                List<AffairRecord> selectcount = affairRecordService.select(recordquerycount);
//                SysUserDTO sysUserDTO = new SysUserDTO();
//                sysUserDTO.setUserRole("zbCheckPerson");
//                List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);
                // 20220324 修改
                //2、中标审核人首先按照公司进行匹配，然后需按照供需中的业务类型对应部门进行分开审核
                //（1）中标审核人按照部门进行划分；比如监理类型->工程部；咨询类型->咨询部；检测类型->检测部；
                //（2）每个业务类型对应的部门审核人只有一个；
                //（3）如果业务类型只有一个，按照部门进行流程的分发；
                //（4）如果业务类型是复合型的，需要复合型的都审核完才行；
                SysUserDTO sysUserDTO = new SysUserDTO();
                // 中标审核人角色
                sysUserDTO.setUserRole("zbCheckPerson");
                // 获取发布单位
                sysUserDTO.setCompanyName(project.getPublishCompany());
                // 获取项目类型
                String projectType = project.getProjectType();
                ArrayList<String>  listdept=new ArrayList<>();
                if(projectType.indexOf("001")!=-1){
                    // 监理类型 对应工程部
                    listdept.add("001");
                }
                if(projectType.indexOf("002")!=-1){
                    listdept.add("003");
                }
                if(projectType.indexOf("003")!=-1){
                    listdept.add("004");
                }
                String deptNames = StringUtils.join(listdept, ",");
                sysUserDTO.setDeptNames(deptNames);

                List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);


                if (selectcount.size() < sysUsers.size()) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("失败：需要所有中标审核人确认");
                    return jsonUtil;
                }
                AffairRecord recordquerycountty = new AffairRecord();
                recordquerycountty.setYwType("000");
                recordquerycountty.setYwId(dto.getSupProjectId());
                recordquerycountty.setCheckStatus("3");
                List<AffairRecord> selectcounttj = affairRecordService.select(recordquerycountty);
                if (selectcounttj.size() < sysUsers.size()) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("失败：都不同意之后才能选择中标，请达成一致意见");
                    return jsonUtil;
                }
                jsonUtil.setFlag(true);
                jsonUtil.setMsg("成功");
                return jsonUtil;

            } else {
                return JsonUtil.error("请点击不同意之后再选择中标");
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }

    }

    // 外部项目 选择之前 先判断 审核意见 审核不同意才能选择中标人
    @RequestMapping("/projectManager/queryCheckRemarkWb")
    @ResponseBody
    public JsonUtil queryCheckRemarkWb(HttpServletRequest request, SupplierProjectDTO dto) {

        JsonUtil jsonUtil = new JsonUtil();
        String projectId = dto.getSupProjectId();
        if (StringUtil.isNotBlank(projectId)) {
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
            if (!"006".equals(project.getStatus())) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("失败：只能操作已发布状态的项目");
                return jsonUtil;
            }
            String checkStatus = project.getIsConfirm();
            if(!"3".equals(checkStatus)){
                return JsonUtil.error("请点击不同意之后再选择中标");
            }

        } else {
            return JsonUtil.error("获取数据失败！！");
        }
        return jsonUtil;
    }


    /**
     * @Author:zhaoyongke
     * @Description: 发送需方--中标消息
     * @Date:14:30 2021/4/7
     */
    public void sendNoticeToXfZb(String projectId, String zbperson,String remark) {
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        SysUser sysUser = sysUserService.selectByPrimaryKey(zbperson);
        String personType = sysUser.getPersonType();
        String realName = "";
        if ("001".equals(personType)) {
            // 个人
            realName = sysUser.getRealName();
        } else {
            realName = sysUser.getLinkPerson();
        }
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getCreateBy());
        notice.setTitle("您发布的" + project.getProjectName() + "项目中标人为" + realName);
        notice.setNoticeType("108");// 中标人确认消息发送
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        notice.setRemark(remark);
        projectNoticeServie.insertSelective(notice);
    }

    public void sendNoticeToXmjl(String  projectId, SupplierProjectAccept acept,String remark){
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        String projectType = project.getProjectType();
        String[] split = projectType.split(",");
        for (int i = 0; i < split.length; i++) {
            String type= split[i];
            String  person="";
            if("001".equals(type)){
                person = acept.getJlManagerPerson();
            }else if("002".equals(type)){
                person = acept.getZxManagerPerson();
            }else if("003".equals(type)){
                person = acept.getJcManagerPerson();
            }else{
                person = acept.getQtMagagerPerson();
            }
            SysUser sysUser = sysUserService.selectByPrimaryKey(acept.getAcceptBy());
            sendNoticeToXmjl(project,sysUser,remark,person);
        }

    }

    /**
     *
     *
     * @param project
     * @param user
     */
    public  void sendNoticeToXmjl(SupplierProject project, SysUser  user,String remark,String sendToId){
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setTitle(project.getProjectName() + "项目, 项目中标人为" + user.getRealName());
        notice.setNoticeType("101");// 中标人确认消息发送
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        notice.setRemark(remark);
        notice.setSendTo(sendToId);
        projectNoticeServie.insertSelective(notice);

    }


    /**
     * @param project
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:45 2021/4/12
     */
    public void sendNoticeToXfTjzb(SupplierProject project, SupplierProjectAccept accept) {
        // 系统推荐出项目中标人后推送消息给 【中标审核人】角色 zbCheckPerson

        // 20220324 修改
        //2、中标审核人首先按照公司进行匹配，然后需按照供需中的业务类型对应部门进行分开审核
        //（1）中标审核人按照部门进行划分；比如监理类型->工程部；咨询类型->咨询部；检测类型->检测部；
        //（2）每个业务类型对应的部门审核人只有一个；
        //（3）如果业务类型只有一个，按照部门进行流程的分发；
        //（4）如果业务类型是复合型的，需要复合型的都审核完才行；
        SysUserDTO sysUserDTO = new SysUserDTO();
        // 中标审核人角色
        sysUserDTO.setUserRole("zbCheckPerson");
        // 获取发布单位
        sysUserDTO.setCompanyName(project.getPublishCompany());
        // 获取项目类型
        String projectType = project.getProjectType();
        ArrayList<String>  listdept=new ArrayList<>();
        if(projectType.indexOf("001")!=-1){
            // 监理类型 对应工程部
            listdept.add("001");
        }
        if(projectType.indexOf("002")!=-1){
            listdept.add("003");
        }
        if(projectType.indexOf("003")!=-1){
            listdept.add("004");
        }
        String deptNames = StringUtils.join(listdept, ",");
        sysUserDTO.setDeptNames(deptNames);

        List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);
        for (int i = 0; i < sysUsers.size(); i++) {
            String acceptBy = accept.getAcceptBy();
            SysUser sysUser = sysUserService.selectByPrimaryKey(acceptBy);
            String personType = sysUser.getPersonType();
            String realName = "";
            if ("001".equals(personType)) {
                // 个人
                realName = sysUser.getRealName();
            } else {
                realName = sysUser.getLinkPerson();
            }
            ProjectNotice notice = new ProjectNotice();
            notice.setLinkId(project.getSupProjectId());
            notice.setIsView("0");
            notice.setSendTo(sysUsers.get(i).getId());
            notice.setTitle(project.getProjectName() + "项目推荐中标人为" + realName + "，请确认是否同意");
            notice.setNoticeType("107");// 内部单位推荐
            notice.setApplicantType("002");// 供需
            notice.setContent(project.getProjectName());
            notice.setCreateDate(DateUtil.getCurrentDateString());
            notice.setTjPerson(acceptBy);
            projectNoticeServie.insertSelective(notice);
        }

    }
    /**
     * @Author:zhaoyongke
     * @Description:
     * @param reDTO
     * @param model
     * @param page
     * @param limit
     * @Date:11:11 2021/4/17
     */
    @ApiOperation(value = "/projectManager/oaInfoEnterfaceQuery", httpMethod = "GET", notes = "查询oa信息")
    @GetMapping(value = "/projectManager/oaInfoEnterfaceQuery")
    @ResponseBody
    public ReType oaInfoEnterfaceQuery(OaReDTO  reDTO, Model model, String page, String limit,String keyword) {
        ReType re = new ReType();
        try{
            String para = "";
            if(StringUtils.isNotBlank(keyword)){
                JSONObject paraObj = new JSONObject();
                paraObj.put("xmmc",keyword);
                para = paraObj.toJSONString();
            }
            // 获取数据字典中配置的值
            List<BaseDict> codeList = baseDictService.selectByTypeCode("SUAUTOCONFIG");
            // 定义查询条件
            Example ex = new Example(OaData.class);
            ex.setOrderByClause("sqrq DESC");
            Example.Criteria cr = ex.createCriteria();
            if (codeList != null && codeList.size() > 0){
                for (BaseDict baseDict : codeList) {
                    if ("htbh".equals(baseDict.getBadtCode()) && StringUtil.isNotBlank(baseDict.getBadtLevel1())){
                        cr.andLike("htbh","%"+baseDict.getBadtLevel1()+"%");
                    }
                    if ("htsqrq".equals(baseDict.getBadtCode()) && StringUtil.isNotBlank(baseDict.getBadtLevel1())){
                        cr.andLike("sqrq","%"+baseDict.getBadtLevel1()+"%");
                    }
                }
            }
//            List<OaData> list = oaDataService.selectAll();
            List<OaData> list = oaDataService.selectByExample(ex);

            if(StringUtils.isNotBlank(page)){
                re.setPageNum(Long.valueOf(page));
            }

            re.setCount(list.size());

            if(StringUtils.isNotBlank(limit)){
                re.setCountOfPage(Long.valueOf(limit));
            }
            re.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re;

    }

    /**
     * @param supplierProjectDTO 监理
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:27 2021/3/27
     */
    @RequestMapping("/projectManager/getSupplierProject")
    @ResponseBody
    public JsonUtil getSupervisorProject(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                re.setFlag(false);
                String supProjectId = supplierProjectDTO.getSupProjectId();
                if(StringUtils.isNotBlank(supProjectId)){
                    SupervisorProject supervisorProject = new SupervisorProject();
                    supervisorProject.setSupProjectId(supProjectId);
                    List<SupervisorProject> supervisorProjectList = supervisorProjectService.select(supervisorProject);
                    if(CollectionUtil.isNotEmpty(supervisorProjectList)){
                        JSONObject resultObj = new JSONObject();
                        resultObj.put("id",supervisorProjectList.get(0).getId());
                        resultObj.put("name",supervisorProjectList.get(0).getProjectName());
                        re.setData(resultObj);
                        re.setFlag(true);
                        return re;
                    }
                    return re;
                }
                log.warn("根据供需项目id查询对应的简历项目时,供需项目id为空!");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }
    }

    /**
     * @param supplierProjectDTO 咨询
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:27 2021/3/27
     */
    @RequestMapping("/projectManager/getZxProject")
    @ResponseBody
    public JsonUtil getZxProject(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                re.setFlag(false);
                String supProjectId = supplierProjectDTO.getSupProjectId();
                if(StringUtils.isNotBlank(supProjectId)){
                    ZxProject zxProject = new ZxProject();
                    zxProject.setSupProjectId(supProjectId);
                    List<ZxProject> zxProjectList = zxProjectService.select(zxProject);
                    if(CollectionUtil.isNotEmpty(zxProjectList)){
                        JSONObject resultObj = new JSONObject();
                        resultObj.put("id",zxProjectList.get(0).getId());
                        resultObj.put("name",zxProjectList.get(0).getProjectName());
                        re.setData(resultObj);
                        re.setFlag(true);
                        return re;
                    }
                    return re;
                }
                log.warn("根据供需项目id查询对应的简历项目时,供需项目id为空!");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }
    }

    /**
     * @param supplierProjectDTO 检测
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:27 2021/3/27
     */
    @RequestMapping("/projectManager/getJcProject")
    @ResponseBody
    public JsonUtil getJcProject(SupplierProjectDTO supplierProjectDTO) {
        if (supplierProjectDTO != null) {
            try {
                JsonUtil re = new JsonUtil();
                re.setFlag(false);
                String supProjectId = supplierProjectDTO.getSupProjectId();
                if(StringUtils.isNotBlank(supProjectId)){
                    JcProject jcProject = new JcProject();
                    jcProject.setSupProjectId(supProjectId);
                    List<JcProject> jcProjectList = jcProjectService.select(jcProject);
                    if(CollectionUtil.isNotEmpty(jcProjectList)){
                        JSONObject resultObj = new JSONObject();
                        resultObj.put("id",jcProjectList.get(0).getId());
                        resultObj.put("name",jcProjectList.get(0).getProjectName());
                        re.setData(resultObj);
                        re.setFlag(true);
                        return re;
                    }
                    return re;
                }
                log.warn("根据供需项目id查询对应的简历项目时,供需项目id为空!");
                return re;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("操作失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("获取数据失败！！");
        }
    }

    @RequestMapping("/rejectCause")
    public String rejectCause(Model model,String caseId,String taskId,String taskName,String businessId){
        //查询字典驳回原因
        BaseDict bd=new BaseDict();
        bd.setBadtTypecode("BHYY001");
        List<BaseDict> list=baseDictService.select(bd);
        model.addAttribute("baseDict",list);
        model.addAttribute("caseId",caseId);
        model.addAttribute("taskId",taskId);
        model.addAttribute("taskName",taskName);
        model.addAttribute("businessId",businessId);
        return "projectManager/rejectCause";
    }

}
